Initial commit: Agentic Prescription Extractor & Studio
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
agents package
|
||||
--------------
|
||||
Modular LangGraph agent definitions for prescription extraction.
|
||||
"""
|
||||
from agents.supervisor_agent import supervisor_node
|
||||
from agents.medicine_strength_agent import medicine_strength_agent
|
||||
from agents.route_agent import route_agent
|
||||
from agents.duration_frequency_agent import duration_frequency_agent
|
||||
from agents.instruction_agent import instruction_agent
|
||||
from agents.aggregator_agent import aggregator_agent
|
||||
from agents.validator_agent import validator_agent
|
||||
from agents.formatter_agent import formatter_node
|
||||
|
||||
__all__ = [
|
||||
"supervisor_node",
|
||||
"medicine_strength_agent",
|
||||
"route_agent",
|
||||
"duration_frequency_agent",
|
||||
"instruction_agent",
|
||||
"aggregator_agent",
|
||||
"validator_agent",
|
||||
"formatter_node",
|
||||
]
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
agents/aggregator_agent.py
|
||||
--------------------------
|
||||
Aggregator Agent:
|
||||
Unifies extracted outputs from all parallel agents into complete clinical records (including additional_instruction),
|
||||
and filters out non-medication noise entities.
|
||||
"""
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, PrescriptionBlock
|
||||
from agents.utils import is_valid_medication_entity, clean_instruction_noise
|
||||
|
||||
|
||||
def aggregator_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregator Agent with noise-proofing entity validation.
|
||||
"""
|
||||
meds = state.get("medicines", [])
|
||||
routes = {r.get("medicine_id", idx + 1): r.get("route", "NONE") for idx, r in enumerate(state.get("routes", []))}
|
||||
dur_freq = {df.get("medicine_id", idx + 1): df for idx, df in enumerate(state.get("durations_frequencies", []))}
|
||||
|
||||
inst_map = {}
|
||||
add_inst_map = {}
|
||||
for idx, ins in enumerate(state.get("instructions", [])):
|
||||
m_id = ins.get("medicine_id", idx + 1)
|
||||
inst_map[m_id] = clean_instruction_noise(ins.get("instruction", "NONE"))
|
||||
add_inst_map[m_id] = clean_instruction_noise(ins.get("additional_instruction", "NONE"))
|
||||
|
||||
aggregated: List[PrescriptionBlock] = []
|
||||
|
||||
for idx, med in enumerate(meds):
|
||||
m_id = med.get("medicine_id", idx + 1)
|
||||
df_entry = dur_freq.get(m_id, {})
|
||||
d_name = med.get("drug_name", "NONE").strip()
|
||||
|
||||
# Noise filter: ensure entity is a valid pharmaceutical drug name
|
||||
if not is_valid_medication_entity(d_name) and len(meds) > 1:
|
||||
continue
|
||||
|
||||
block: PrescriptionBlock = {
|
||||
"Drug_name": d_name,
|
||||
"strength": med.get("strength", "NONE"),
|
||||
"frequency": df_entry.get("frequency", "NONE"),
|
||||
"duration": df_entry.get("duration", "NONE"),
|
||||
"route": routes.get(m_id, "NONE"),
|
||||
"instruction": inst_map.get(m_id, "NONE"),
|
||||
"additional_instruction": add_inst_map.get(m_id, "NONE"),
|
||||
}
|
||||
aggregated.append(block)
|
||||
|
||||
log_entry = {
|
||||
"agent": "Aggregator",
|
||||
"action": f"Aggregated {len(aggregated)} noise-proof medicine block(s)",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"aggregated_blocks": aggregated,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
agents/duration_frequency_agent.py
|
||||
----------------------------------
|
||||
Duration & Frequency Agent:
|
||||
Drift-proof extractor for administration frequencies and duration spans across arbitrary clinical expressions.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, DurationFrequencyItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
GENERAL_FREQUENCY_PATTERNS = [
|
||||
r"up\s+to\s+\w+\s+times\s+daily(?:\s+as\s+needed)?",
|
||||
r"every\s+\d+(?:\s+to\s+\d+)?\s*(?:hours?|hrs?|days?|weeks?|months?)",
|
||||
r"every\s+(?:morning|night|evening|afternoon|bedtime|other\s+day)",
|
||||
r"(?:twice|once|thrice|three\s+times|four\s+times|\d+\s+times)\s+daily\s*\([0-9\-\/]+\)",
|
||||
r"\b\d+-\d+-\d+(?:-\d+)?\b",
|
||||
r"(?:twice|once|thrice|three\s+times|four\s+times|\d+\s+times)\s+(?:daily|a\s+day|per\s+day|a\s+week|weekly|a\s+month|monthly)",
|
||||
r"(?:once|twice|thrice)\s+weekly",
|
||||
r"three\s+times\s+daily",
|
||||
r"four\s+times\s+daily",
|
||||
r"twice\s+daily",
|
||||
r"once\s+daily",
|
||||
r"thrice\s+daily",
|
||||
r"throughout\s+the\s+day",
|
||||
r"single\s+dose",
|
||||
r"stat\s+dose",
|
||||
r"as\s+needed\s*\([A-Za-z]+\)",
|
||||
r"as\s+needed(?:\s+for\s+[a-zA-Z\s]+)?",
|
||||
r"early\s+morning",
|
||||
r"at\s+bedtime",
|
||||
r"\bdaily\b",
|
||||
r"\b(?:OD|BD|TID|QID|QDS|TDS|BID|PRN|SOS|HS|STAT|q\d+h|q\d+-\d+h)\b",
|
||||
]
|
||||
|
||||
GENERAL_DURATION_PATTERNS = [
|
||||
r"\b(?:for\s+|duration\s+of\s+|till\s+|until\s+|upto\s+|up\s+to\s+|for\s+upto\s+|for\s+up\s+to\s+|for\s+next\s+|next\s+|about\s+|around\s+|approx(?:\s+)?|for\s+around\s+|for\s+about\s+|x\s*)(\d+\s*(?:days?|d|weeks?|wks?|months?|mo|years?|hrs?|hours?)|day\s+one|single\s+day|\d+\s*to\s*\d+\s*(?:days?|weeks?|months?)|no\s+more\s+than\s+\d+\s+days?)\b",
|
||||
r"\b(until\s+[a-zA-Z\s]{3,30})\b",
|
||||
r"\b(\d+\s*(?:days?|weeks?|months?))\b",
|
||||
]
|
||||
|
||||
|
||||
def duration_frequency_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Duration & Frequency Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("duration_frequency_agent", "")
|
||||
|
||||
extracted_dur_freq: List[DurationFrequencyItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.DURATION_FREQUENCY_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
freq = item.get("frequency", "NONE")
|
||||
dur = item.get("duration", "NONE")
|
||||
if not is_placeholder(freq) and not is_placeholder(dur):
|
||||
extracted_dur_freq.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"frequency": freq,
|
||||
"duration": dur,
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_dur_freq:
|
||||
segments = segment_prescription(input_text)
|
||||
|
||||
# Check global plural/broadcast coreference (e.g. "Both should be taken twice daily", "All medicines are once daily")
|
||||
global_plural_freq = "NONE"
|
||||
global_plural_dur = "NONE"
|
||||
plural_match = re.search(r"(?i)\b(?:both(?:\s+of\s+them|\s+medicines|\s+drugs|\s+tablets|\s+capsules)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\s+(?:should\s+be\s+taken|are\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|should\s+be\s+given|should\s+be|are|must\s+be)\s+([^,\.\n;!]+)", input_text)
|
||||
if plural_match:
|
||||
cand_p = plural_match.group(1).strip()
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
fm = re.search(fp, cand_p, re.IGNORECASE)
|
||||
if fm:
|
||||
global_plural_freq = fm.group(0).strip()
|
||||
break
|
||||
for dp in GENERAL_DURATION_PATTERNS:
|
||||
dm = re.search(dp, input_text, re.IGNORECASE)
|
||||
if dm:
|
||||
global_plural_dur = dm.group(1).strip()
|
||||
break
|
||||
|
||||
# Check singular coreference (e.g. "It should be taken 4 times a day", "This medicine is to be taken twice daily")
|
||||
global_singular_freq = "NONE"
|
||||
singular_match = re.search(r"(?i)\b(?:it\s+(?:should\s+be\s+taken|is\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|is\s+taken)|take\s+(?:it|this(?:\s+medicine)?))\s+([^,\.\n;!]+)", input_text)
|
||||
if singular_match:
|
||||
cand_s = singular_match.group(1).strip()
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
fm = re.search(fp, cand_s, re.IGNORECASE)
|
||||
if fm:
|
||||
global_singular_freq = fm.group(0).strip()
|
||||
break
|
||||
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
|
||||
# 1. Frequency (search in first 100 chars of clause first to avoid matching trailing advice)
|
||||
core_clause = clause[:100]
|
||||
freq = "NONE"
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
f_match = re.search(fp, core_clause, re.IGNORECASE)
|
||||
if f_match:
|
||||
matched_freq = f_match.group(0).strip()
|
||||
matched_freq = re.sub(r"(?i)\s+(?:before|after)\s+(?:food|breakfast|meals|lunch|dinner)$", "", matched_freq).strip()
|
||||
freq = matched_freq
|
||||
break
|
||||
|
||||
if freq == "NONE":
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
f_match = re.search(fp, clause, re.IGNORECASE)
|
||||
if f_match:
|
||||
matched_freq = f_match.group(0).strip()
|
||||
matched_freq = re.sub(r"(?i)\s+(?:before|after)\s+(?:food|breakfast|meals|lunch|dinner)$", "", matched_freq).strip()
|
||||
freq = matched_freq
|
||||
break
|
||||
|
||||
if freq == "NONE":
|
||||
if global_plural_freq != "NONE":
|
||||
freq = global_plural_freq
|
||||
elif global_singular_freq != "NONE" and (len(segments) == 1 or m_id == len(segments)):
|
||||
freq = global_singular_freq
|
||||
|
||||
# 2. Duration
|
||||
dur = "NONE"
|
||||
for dp in GENERAL_DURATION_PATTERNS:
|
||||
d_match = re.search(dp, clause, re.IGNORECASE)
|
||||
if d_match:
|
||||
dur = d_match.group(1).strip()
|
||||
break
|
||||
|
||||
if dur == "NONE" and global_plural_dur != "NONE":
|
||||
dur = global_plural_dur
|
||||
|
||||
extracted_dur_freq.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": "",
|
||||
"frequency": freq,
|
||||
"duration": dur,
|
||||
})
|
||||
|
||||
return {"durations_frequencies": extracted_dur_freq}
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
agents/formatter_agent.py
|
||||
-------------------------
|
||||
Formatter Node:
|
||||
Generates the exact structured block representation (including additional_instruction) with zero extraneous commentary.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState
|
||||
|
||||
|
||||
def formatter_node(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Formatter Node:
|
||||
Produces the strict structured blocks format with no explanations, notes, or moralizing.
|
||||
"""
|
||||
blocks = state.get("aggregated_blocks", [])
|
||||
output_lines = []
|
||||
|
||||
for b in blocks:
|
||||
output_lines.append(f"Drug_name: {b.get('Drug_name', 'NONE')}")
|
||||
output_lines.append(f"strength: {b.get('strength', 'NONE')}")
|
||||
output_lines.append(f"frequency: {b.get('frequency', 'NONE')}")
|
||||
output_lines.append(f"duration: {b.get('duration', 'NONE')}")
|
||||
output_lines.append(f"route: {b.get('route', 'NONE')}")
|
||||
output_lines.append(f"instruction: {b.get('instruction', 'NONE')}")
|
||||
output_lines.append(f"additional_instruction: {b.get('additional_instruction', 'NONE')}")
|
||||
|
||||
final_text = "\n".join(output_lines)
|
||||
|
||||
log_entry = {
|
||||
"agent": "Formatter",
|
||||
"action": "Generated final structured clinical blocks",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"final_output": final_text,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
"""
|
||||
agents/instruction_agent.py
|
||||
---------------------------
|
||||
Instruction Agent:
|
||||
Dynamic natural language extractor for primary administration instructions and additional clinical instructions:
|
||||
1. 'instruction': Primary administration timing, meals, preparation techniques, device usage, PRN indications, times-of-day.
|
||||
2. 'additional_instruction': Clinical follow-up, evaluation, monitoring, reassessment, adverse effect warnings,
|
||||
titration conditions, course completion rules, cross-drug cautions, and dietary/lifestyle guidance.
|
||||
Fully drift-proof and punctuation-independent for continuous voice speech.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, InstructionItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
# Common Action verbs that introduce a new medication clause
|
||||
MED_ACTION_VERB_START = r"(?i)^(?:take\s+(?!(?:walks?|rest|care|steam))\w+|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill|inject|infuse|gently\s+massage|massage|cleanse)\b"
|
||||
|
||||
# Verbs / phrases that naturally signal follow-up, evaluation, precaution, warnings, or lifestyle advice
|
||||
INDEPENDENT_ADVICE_START = (
|
||||
r"(?i)^(?:return\s+for|return\s+if|return\s+after|return\s+to|come\s+back|follow\s+up|review\s+if|review\s+after|"
|
||||
r"meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+|the\s+)?doctor|"
|
||||
r"get\s+reassessed|seek\s+reassessment|seek\s+medical\s+review|seek\s+urgent|seek\s+immediate|seek|"
|
||||
r"consult\s+immediately|consult\s+your|consult|"
|
||||
r"contact\s+the\s+clinic|contact\s+your|report\s+immediately|report\s+if|report|"
|
||||
r"visit\s+the\s+emergency|visit\s+the\s+clinic|visit|"
|
||||
r"revisit\s+the\s+clinic|revisit|"
|
||||
r"arrange\s+for|schedule\s+a|schedule|"
|
||||
r"repeat\s+a|repeat|re-?test\s+your|re-?test|"
|
||||
r"do\s+not\s+stop|do\s+not\s+exceed|do\s+not\s+delay|do\s+not\s+squeeze|do\s+not|"
|
||||
r"avoid\s+taking|avoid\s+exposure|avoid\s+lifting|avoid\s+squatting|avoid\s+smoking|avoid\s+drinking|avoid|"
|
||||
r"strictly\s+avoid|"
|
||||
r"discontinue\s+once|discontinue|stop\s+taking|stop\s+if|stop|"
|
||||
r"keep\s+the\s+dressing|keep\s+the\s+ear|keep\s+a\s+regular|keep\s+a\s+headache|keep\s+a|keep|"
|
||||
r"maintain\s+a|maintain\s+generous|maintain|"
|
||||
r"stick\s+to\s+a|stick\s+to|"
|
||||
r"include\s+dark|include\s+green|include|"
|
||||
r"limit\s+your|limit\s+fluid|limit|"
|
||||
r"practice\s+pursed-lip|practice|"
|
||||
r"brush\s+gently|brush|"
|
||||
r"perform\s+steam\s+inhalation|perform\s+steam|perform\s+gentle|perform|"
|
||||
r"use\s+saline\s+nasal|use\s+saline|"
|
||||
r"drink\s+plenty|drink\s+2|drink\s+warm|drink|"
|
||||
r"consume\s+plenty|consume\s+warm|stay\s+well-hydrated|"
|
||||
r"apply\s+local\s+hot|apply\s+ice\s+packs?|"
|
||||
r"sponge\s+the\s+body|sponge\s+forehead|sponge|"
|
||||
r"(?:also\s+)?take\s+walks?|go\s+for\s+walks?|take\s+rest|take\s+steam|"
|
||||
r"wear\s+loose|monitor\s+your|monitor\s+weight|monitor\s+blood|monitor\s+inr|monitor|"
|
||||
r"be\s+sure\s+to\s+rinse|rinse\s+your\s+mouth\s+thoroughly|rinse\s+mouth\s+after|"
|
||||
r"if\s+headache|if\s+blood\s+pressure|if\s+fever|if\s+symptoms|if\s+pain|if\s+rash|if\s+numbness|if\s+severe|if\s+ulcers|if\s+condition|if\s+breathing|if\s+dizziness|"
|
||||
r"(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage))\b"
|
||||
)
|
||||
|
||||
# Robust punctuation-independent clinical advice pattern (captures continuous speech advice)
|
||||
CONTINUOUS_ADVICE_SPAN_PATTERNS = [
|
||||
r"(?i)\b(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not\s+go\s+away|does\s+not\s+clear|persists|worsens|increases|crosses\s+\d+|develops|occurs|remains\s+high|subsides|heals|drops\s+to\s+normal)(?:,\s*|\s+)?(?:(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+\d+\s*(?:mgs?|mg|g|mcg|ml))?|Meet\s+(?:the\s+)?doctor|come\s+visit\s+(?:the\s+|your\s+)?doctor|consult\s+(?:your\s+)?doctor|seek\s+medical\s+review|visit\s+(?:the\s+)?emergency|report\s+immediately)?)\b",
|
||||
r"(?i)\b(?:(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)\s+(?:by\s+)?\d+\s*(?:mgs?|mg|g|mcg|ml)?(?:,\s*|\s+)?(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not\s+go\s+away|does\s+not\s+clear|persists|worsens|increases|crosses\s+\d+|develops|occurs|remains\s+high|subsides|heals))?)\b",
|
||||
r"(?i)\b(?:meet\s+(?:the\s+)?doctor)\b",
|
||||
r"(?i)\b(?:please\s+see\s+me(?:\s+after\s+\d+\s+days?)?)\b",
|
||||
r"(?i)\b(?:see\s+(?:your\s+|the\s+)?doctor(?:\s+after\s+\d+\s+days?)?)\b",
|
||||
r"(?i)\b(?:(?:also\s+)?take\s+walks?(?:\s+after\s+dinner)?(?:\s+and\s+it\s+will\s+reduce\s+your\s+headaches)?)\b",
|
||||
r"(?i)\b(?:go\s+for\s+(?:morning\s+)?walks?(?:\s+daily)?)\b",
|
||||
r"(?i)\b(?:return\s+for(?:\s+evaluation|\s+review|\s+a\s+follow-up)?(?:\s+after\s+completing\s+the\s+course)?)\b",
|
||||
r"(?i)\b(?:come\s+(?:back\s+)?for\s+review(?:\s+with\s+[a-zA-Z\s]+)?)\b",
|
||||
r"(?i)\b(?:sponge\s+(?:the\s+)?(?:body|forehead)(?:\s+with\s+cold\s+water)?(?:\s+if\s+[a-zA-Z\s]+)?)\b",
|
||||
r"(?i)\b(?:discontinue\s+(?:once|if)\s+[a-zA-Z\s]+?)\b",
|
||||
r"(?i)\b(?:do\s+not\s+stop\s+(?:the\s+)?antibiotic\s+course[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:avoid\s+(?:lifting\s+heavy\s+weights|squatting|hot\s+baths|scratching|smoking|alcohol|spicy|sour)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:stick\s+to\s+a\s+bland\s+diet[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:maintain\s+(?:a\s+low-glycemic|generous\s+hydration|a\s+regular\s+sleep)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:include\s+(?:dark\s+)?green\s+leafy[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:drink\s+(?:plenty|2\.5|\d+\s+liters)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:apply\s+(?:local\s+)?hot\s+water\s+fomentation[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:keep\s+(?:the\s+)?(?:blistered|affected|skin|dressing|ear)\s+area\s+clean\s+and\s+dry)\b",
|
||||
r"(?i)\b(?:avoid\s+close\s+physical\s+contact[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:return\s+if\s+the\s+rash\s+involves[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:come\s+(?:and\s+)?visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"(?i)\b(?:visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"(?i)\b(?:take\s+(?:regular\s+|warm\s+|cold\s+|plenty\s+of\s+|sufficient\s+|clean\s+)?(?:water|fluids?))\b",
|
||||
r"(?i)\b(?:(?:use\s+)?saline\s+nasal\s+irrigations?(?:\s+twice\s+daily)?)\b",
|
||||
r"(?i)\b(?:perform\s+steam\s+inhalation(?:\s+daily)?)\b",
|
||||
r"(?i)\b(?:seek\s+reassessment\s+if\s+[a-zA-Z\s\-]+?develops?)\b",
|
||||
]
|
||||
|
||||
# Intra-clause primary administration expressions (times of day, meals, devices, preparations, PRN)
|
||||
PRIMARY_INSTRUCTION_PATTERNS = [
|
||||
# Natural Times of Day
|
||||
r"\b(?:morning\s+night|morning\s+afternoon\s+night|morning\s+and\s+night|morning\s+and\s+evening|morning\s+evening|day\s+and\s+night|early\s+morning|at\s+noon|at\s+bedtime|at\s+night|in\s+the\s+morning(?:\s+after\s+breakfast)?|in\s+the\s+evening|in\s+the\s+afternoon|before\s+bed(?:time)?)\b",
|
||||
|
||||
# Specific Meal Timings
|
||||
r"\b\d+\s+minutes\s+before\s+breakfast\s+and\s+dinner\b",
|
||||
r"\b\d+\s+minutes\s+before\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+minutes\s+after\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+hours?\s+before\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+hours?\s+after\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b(?:before|after)\s+(?:breakfast|lunch|dinner|meals?|food)\b",
|
||||
r"\b(?:strictly\s+after\s+food|strictly\s+with\s+food|strictly\s+with\s+meals(?:\s+to\s+avoid\s+[^,\.\n]+)?)\b",
|
||||
r"\b(?:on\s+an?\s+empty\s+stomach|empty\s+stomach|with\s+meals|with\s+food)\b",
|
||||
|
||||
# Devices, Inhalers & Administration Techniques
|
||||
r"\busing\s+(?:the\s+)?Revolizer\s+device\b",
|
||||
r"\busing\s+(?:your\s+)?dry\s+powder\s+inhaler(?:\s+and\s+rinse\s+your\s+mouth\s+immediately)?\b",
|
||||
r"\bvia\s+an?\s+MDI\s+spacer(?:\s+as\s+needed)?\b",
|
||||
r"\binto\s+each\s+nostril\b",
|
||||
r"\b\d+\s+sprays?\s+into\s+each\s+nostril\b",
|
||||
r"\b\d+\s+drops?\s+into\s+(?:each\s+nostril|the\s+affected\s+ear|both\s+eyes|left\s+eye|right\s+eye)(?:\s+for\s+no\s+more\s+than\s+\d+\s+days)?(?:\s+ensuring\s+the\s+eardrum\s+is\s+intact)?\b",
|
||||
r"\b\d+\s+teaspoons?\s+diluted\s+in\s+a\s+full\s+glass\s+of\s+water\b",
|
||||
r"\b\d+\s*ml\s+diluted\s+with\s+equal\s+parts\s+water\b",
|
||||
r"\bdissolve\s+(?:one\s+sachet\s+)?in\s+one\s+liter\s+of\s+clean\s+drinking\s+water\s+to\s+consume\s+throughout\s+the\s+day\b",
|
||||
r"\b(?:dissolved\s+in\s+water|mixed\s+in\s+milk|effervescent\s+tablet\s+dissolved\s+in\s+water)\b",
|
||||
r"\bslowly\s+dissolve\s+(?:one\s+antiseptic\s+lozenge\s+)?in\s+your\s+mouth[^\.\n,]*",
|
||||
r"\bapply\s+a\s+thin\s+layer\s+along\s+the\s+clean\s+suture\s+line\b",
|
||||
r"\bapply\s+(?:gel\s+)?sparingly\s+to\s+active\s+pimples[^\.\n,]*",
|
||||
r"\bapply\s+a\s+pea-sized\s+amount\s+all\s+over\s+the\s+face[^\.\n,]*",
|
||||
r"\bapply\s+broad-spectrum\s+sunscreen\s+SPF\s+50[^\.\n,]*",
|
||||
r"\bwithout\s+swallowing\s+or\s+eating\s+for\s+\d+\s+minutes\b",
|
||||
r"\brinse\s+your\s+mouth\s+with\s+\d+\s*ml[^\.\n,]*for\s+\d+\s+minute\b",
|
||||
r"\brinse\s+your\s+mouth\s+thoroughly\s+after\s+using\s+the\s+inhaler\b",
|
||||
r"\brinse\s+mouth\s+(?:after\s+(?:using\s+the\s+inhaler|use))?\b",
|
||||
r"\bswallow\s+(?:tablets?|capsules?|medicine)?\s*whole(?:\s+without\s+crushing|\s+do\s+not\s+crush)?\b",
|
||||
r"\bwith\s+a\s+full\s+glass\s+of\s+water\b",
|
||||
r"\bgargle\s+with\s+warm\s+Povidone-iodine\s+mouthwash[^\.\n,]*",
|
||||
r"\bcleanse\s+the\s+skin\s+gently\s+using\s+Chlorhexidine\s+wash[^\.\n,]*",
|
||||
r"\bapply\s+a\s+dab\s+of[^\.\n,]*over\s+the\s+mouth\s+ulcers\b",
|
||||
r"\bapply\s+a\s+thin\s+layer\s+of[^\.\n,]*to\s+the\s+affected\s+patches\b",
|
||||
r"\bapply\s+(?:a\s+bland\s+moisturizing\s+)?paraffin\s+lotion\s+over\s+dry\s+skin\s+areas\b",
|
||||
|
||||
# PRN & Specific Indications
|
||||
r"\bfor\s+(?:facial\s+pain\s+or\s+fever|nausea|throat\s+discomfort|sudden\s+breathlessness|episodic\s+pelvic\s+discomfort|pain\s+relief|fever|pain|cough|headache)\b",
|
||||
r"\bto\s+relieve\s+itching\b",
|
||||
r"\bfor\s+the\s+first\s+\d+\s+days\b",
|
||||
]
|
||||
|
||||
# Secondary / Per-drug warnings & titrations
|
||||
PER_DRUG_SECONDARY_PATTERNS = [
|
||||
r"ensuring\s+it\s+is\s+kept\s+at\s+least\s+\d+\s+hours\s+apart\s+from\s+[^,\.\n]+",
|
||||
r"do\s+not\s+exceed\s+\d+\s+doses\s+within\s+\d+\s+hours",
|
||||
r"without\s+starting\s+new\s+uric\s+acid\s+reducers[^\.\n,]*",
|
||||
r"alongside\s+[^,\.\n]+\s+to\s+optimize\s+[^,\.\n]+",
|
||||
r"alongside\s+[^,\.\n]+\s+to\s+maximize\s+[^,\.\n]+",
|
||||
r"(?:for\s+)?(?:a\s+)?strict\s+maximum\s+of\s+\d+\s+days?",
|
||||
r"for\s+no\s+more\s+than\s+\d+\s+days?",
|
||||
r"(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+[^,\.\n]+)?(?:\s+if\s+[^,\.\n]+)?",
|
||||
r"if\s+[^,\.\n]+?\s+(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+[^,\.\n]+)?",
|
||||
r"discontinue\s+once\s+[^,\.\n]+",
|
||||
r"stop\s+(?:taking\s+)?if\s+[^,\.\n]+",
|
||||
r"do\s+not\s+stop\s+(?:the\s+)?(?:antibiotic\s+)?course\s+early[^\.\n]*",
|
||||
r"complete\s+(?:the\s+)?full\s+course[^\.\n]*",
|
||||
]
|
||||
|
||||
DRUG_CLASS_MAP = {
|
||||
"antibiotic": ["amoxicillin", "augmentin", "azithromycin", "ciprofloxacin", "ofloxacin", "cefixime", "doxycycline", "clavulanate", "penicillin", "phexin", "clarithromycin", "nitrofurantoin", "cefuroxime", "cephalexin", "cefpodoxime"],
|
||||
"iron": ["ferrous", "iron", "folic", "autrin", "orofer"],
|
||||
"inhaler": ["budecort", "foracort", "asthalin", "seretide", "tiova", "fluticasone", "formoterol", "salbutamol", "rotacap", "budesonide", "tiotropium", "levosalbutamol"],
|
||||
"painkiller": ["paracetamol", "crocin", "ibuprofen", "combiflam", "tramadol", "aceclofenac", "diclofenac", "naproxen", "etoricoxib"],
|
||||
"antacid": ["pantop", "pan", "omeprazole", "rabeprazole", "esomeprazole", "gelusil", "digene", "sucralfate", "pantoprazole"],
|
||||
"eye drops": ["moxifloxacin", "ciprofloxacin", "tobramycin", "carboxymethylcellulose", "tears"],
|
||||
"ear drops": ["ciprofloxacin with dexamethasone", "ear drops"],
|
||||
}
|
||||
|
||||
|
||||
def deduplicate_phrases(inst_list: List[str]) -> List[str]:
|
||||
"""Helper to clean duplicate/contained strings, prioritizing complete compound clauses."""
|
||||
filtered: List[str] = []
|
||||
sorted_candidates = sorted([c.strip() for c in inst_list if c and not is_placeholder(c)], key=len, reverse=True)
|
||||
for cand in sorted_candidates:
|
||||
c_clean = cand.strip()
|
||||
if any(c_clean.lower() != other.lower() and c_clean.lower() in other.lower() for other in filtered):
|
||||
continue
|
||||
if c_clean not in filtered and c_clean.lower() not in [f.lower() for f in filtered]:
|
||||
filtered.append(c_clean)
|
||||
return filtered
|
||||
|
||||
|
||||
def instruction_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Instruction Agent with dynamic punctuation-independent natural language reasoning.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("instruction_agent", "")
|
||||
|
||||
extracted_inst: List[InstructionItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.INSTRUCTION_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
inst = item.get("instruction", "NONE")
|
||||
add_inst = item.get("additional_instruction", "NONE")
|
||||
if not is_placeholder(inst):
|
||||
extracted_inst.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"instruction": inst,
|
||||
"additional_instruction": add_inst if not is_placeholder(add_inst) else "NONE",
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_inst:
|
||||
segments = segment_prescription(input_text)
|
||||
total_meds = len(segments)
|
||||
|
||||
# 1. Punctuation-Independent Clinical Advice Discovery:
|
||||
clean_input = re.sub(r"(\d+),(\d+)", r"\1\2", input_text)
|
||||
clean_input = re.sub(r"\.\s*((?:Once|Twice|Thrice|\d+\s+times|Every|Daily|At\s+bedtime|In\s+the\s+morning)[^\.,;]+?),\s*(take|administer|give|start|apply|inhale|instill)", r" \1. \2", clean_input, flags=re.IGNORECASE)
|
||||
# A. Sentence-level discovery
|
||||
raw_sentences = [s.strip() for s in re.split(r"(?<!\d)\.(?!\d)|[\n;!]", clean_input) if s.strip()]
|
||||
global_clinical_advice: List[str] = []
|
||||
|
||||
for sent in raw_sentences:
|
||||
s_clean = re.sub(r"^[\s,.\-]+", "", sent).strip()
|
||||
s_lower = s_clean.lower()
|
||||
is_class_specific = any(re.search(rf"\b{re.escape(k)}\b", s_lower) for k in DRUG_CLASS_MAP.keys())
|
||||
has_action = bool(re.search(r"(?i)\b(?:take|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill)\b", s_clean))
|
||||
has_dose_form = bool(re.search(r"(?i)(?:\d+\s*(?:mg|g|mcg|ml|iu|%)|\b(?:tablets?|capsules?|rotacaps?|vials?|sachets?|syrups?|gels?|drops?|sprays?|ointments?|creams?|lotions?)\b)", s_clean))
|
||||
is_med_sentence = (has_action and has_dose_form) or bool(re.search(MED_ACTION_VERB_START, s_clean))
|
||||
is_advice_sentence = bool(re.search(INDEPENDENT_ADVICE_START, s_clean))
|
||||
is_freq_schedule_sentence = bool(re.search(r"(?i)\b(?:it\s+(?:should\s+be\s+taken|is\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|is\s+taken)|take\s+(?:it|this(?:\s+medicine)?)|both(?:\s+of\s+them)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\b", s_clean)) and bool(re.search(r"(?i)\b(?:\d+\s+times|once|twice|thrice|daily|every|at\s+bedtime|morning|night)\b", s_clean))
|
||||
|
||||
if not is_class_specific and not is_med_sentence and not is_freq_schedule_sentence and (is_advice_sentence or len(s_clean) >= 10):
|
||||
if not re.search(r"^\s*(?:Morning\s+Night|\d+\s*(?:mg|g|mcg|ml))\b", s_clean, re.IGNORECASE):
|
||||
if s_clean and s_clean not in global_clinical_advice:
|
||||
global_clinical_advice.append(s_clean)
|
||||
|
||||
# B. Continuous-Span discovery (finds unpunctuated advice phrases anywhere in raw speech)
|
||||
for adv_pat in CONTINUOUS_ADVICE_SPAN_PATTERNS:
|
||||
matches = re.finditer(adv_pat, input_text, re.IGNORECASE)
|
||||
for m in matches:
|
||||
span_txt = m.group(0).strip()
|
||||
span_lower = span_txt.lower()
|
||||
is_class_specific = any(re.search(rf"\b{re.escape(k)}\b", span_lower) for k in DRUG_CLASS_MAP.keys())
|
||||
if not is_class_specific and len(span_txt) >= 5:
|
||||
if span_txt not in global_clinical_advice and not any(span_txt.lower() in g.lower() for g in global_clinical_advice):
|
||||
global_clinical_advice.append(span_txt)
|
||||
|
||||
for idx, s in enumerate(segments):
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
clause_lower = clause.lower()
|
||||
|
||||
# Isolate the core medication administration clause from trailing advice
|
||||
core_med_clause = re.split(
|
||||
r"(?i)\b(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not|persists|worsens|increases|crosses|develops|remains)|meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+)?doctor|(?:also\s+)?take\s+walks|take\s+walks|return\s+for|come\s+for|sponge)\b",
|
||||
clause
|
||||
)[0].strip()
|
||||
|
||||
# Derive current medicine name / stem from this clause
|
||||
med_lead_match = re.search(
|
||||
r"(?:take|administer|give|consume|dissolve|inhale|apply|put|instill|start|cleanse|gently\s+massage|massage)?\s*(?:one|two|three|10\s*ml)?\s*(?:tablet|tab|capsule|cap|rotacap|vial|sachet|puff|sprays?|drops?|teaspoons?|dab\s+of|thin\s+layer\s+of|pea-sized\s+amount\s+of)?\s*(?:of\s+)?([A-Za-z0-9\-]+)",
|
||||
core_med_clause,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
med_stem = med_lead_match.group(1).lower() if med_lead_match else ""
|
||||
if med_stem in ("one", "two", "three", "tab", "tablet", "capsule", "vial", "sachet", "none", "administer", "take", "start", "apply", "cleanse", "this", "print"):
|
||||
med_stem = ""
|
||||
|
||||
primary_insts: List[str] = []
|
||||
secondary_insts: List[str] = []
|
||||
|
||||
# 2a. Primary patterns in core medication clause (timing, meal, device, times-of-day)
|
||||
for pat in PRIMARY_INSTRUCTION_PATTERNS:
|
||||
matches = re.finditer(pat, core_med_clause, re.IGNORECASE)
|
||||
for m in matches:
|
||||
matched_txt = m.group(0).strip()
|
||||
matched_lower = matched_txt.lower()
|
||||
|
||||
# Guard: Inhaler device instructions should only attach to inhaler/respiratory medications
|
||||
if "inhaler" in matched_lower and not any(k in core_med_clause[:80].lower() for k in ("inhal", "rotacap", "revolizer", "puff", "spacer", "budesonide", "tiotropium", "levosalbutamol", "fluticasone")):
|
||||
continue
|
||||
|
||||
if matched_txt.lower() not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(matched_txt)
|
||||
|
||||
# 2b. Secondary patterns in this clause (titrations, precautions, course completion)
|
||||
for pat in PER_DRUG_SECONDARY_PATTERNS:
|
||||
matches = re.finditer(pat, clause, re.IGNORECASE)
|
||||
for m in matches:
|
||||
matched_txt = m.group(0).strip()
|
||||
matched_lower = matched_txt.lower()
|
||||
# Guard: check class mismatch
|
||||
is_mismatched = False
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", matched_lower) and not (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
is_mismatched = True
|
||||
break
|
||||
if not is_mismatched and matched_txt.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(matched_txt)
|
||||
|
||||
# 2c. Standalone sentences matching this drug or its class
|
||||
for sent in raw_sentences:
|
||||
sent_lower = sent.lower()
|
||||
|
||||
# Check if this sentence explicitly belongs to a DIFFERENT medicine
|
||||
is_other_med = False
|
||||
for other_s in segments:
|
||||
if other_s["medicine_id"] != m_id:
|
||||
other_lead = re.search(
|
||||
r"(?:take|start|administer|give|consume|dissolve|inhale|apply|put|instill|cleanse|massage)?\s*(?:one|two|three)?\s*(?:tablet|tab|capsule|cap|rotacap|vial|sachet)?\s*(?:of\s+)?([A-Za-z0-9\-]+)",
|
||||
other_s["clause"],
|
||||
re.IGNORECASE,
|
||||
)
|
||||
other_stem = other_lead.group(1).lower() if other_lead else ""
|
||||
if other_stem and len(other_stem) >= 3 and other_stem not in ("one", "two", "three", "tab", "tablet", "capsule", "none", "this", "print") and other_stem in sent_lower and other_stem != med_stem:
|
||||
is_other_med = True
|
||||
break
|
||||
if is_other_med:
|
||||
continue
|
||||
|
||||
# Check explicit drug name or stem mention in the sentence
|
||||
mentions_this_drug = (med_stem and len(med_stem) >= 3 and med_stem in sent_lower)
|
||||
|
||||
# Check class mention (e.g. "antibiotic", "iron", "inhaler", "painkiller")
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", sent_lower) and (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
mentions_this_drug = True
|
||||
|
||||
# Check broadcast/plural coreference (e.g. "Both should be taken twice daily after meals")
|
||||
is_broadcast_sent = bool(re.search(r"(?i)\b(?:both(?:\s+of\s+them|\s+medicines|\s+drugs|\s+tablets|\s+capsules)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\s+(?:should\s+be\s+taken|are\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|should\s+be\s+given|should\s+be|are|must\s+be)\b", sent))
|
||||
|
||||
# If sentence matches this drug or is generic unassigned advice in a 1-med prescription
|
||||
if mentions_this_drug or is_broadcast_sent or (total_meds == 1 and not is_other_med):
|
||||
is_sent_pure_advice = bool(re.search(INDEPENDENT_ADVICE_START, sent.strip())) or any(re.search(p, sent, re.IGNORECASE) for p in CONTINUOUS_ADVICE_SPAN_PATTERNS)
|
||||
# Only check primary patterns if this is NOT a pure advice/lifestyle sentence
|
||||
if not is_sent_pure_advice:
|
||||
for pat in PRIMARY_INSTRUCTION_PATTERNS:
|
||||
s_match = re.search(pat, sent, re.IGNORECASE)
|
||||
if s_match:
|
||||
s_txt = s_match.group(0).strip()
|
||||
s_lower = s_txt.lower()
|
||||
if "inhaler" in s_lower and not any(k in clause[:80].lower() for k in ("inhal", "rotacap", "revolizer", "puff", "spacer", "budesonide", "tiotropium", "levosalbutamol", "fluticasone")):
|
||||
continue
|
||||
if s_txt.lower() not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(s_txt)
|
||||
# Check secondary patterns
|
||||
for pat in PER_DRUG_SECONDARY_PATTERNS:
|
||||
s_match = re.search(pat, sent, re.IGNORECASE)
|
||||
if s_match:
|
||||
s_txt = s_match.group(0).strip()
|
||||
s_lower = s_txt.lower()
|
||||
is_mismatched = False
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", s_lower) and not (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
is_mismatched = True
|
||||
break
|
||||
if not is_mismatched and s_txt.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(s_txt)
|
||||
|
||||
# 2d. Inhaler device care (Primary)
|
||||
if any(k in clause[:80].lower() for k in ("budecort", "foracort", "inhaler", "rotacap", "asthalin", "budesonide", "revolizer", "tiotropium")):
|
||||
for lf in ("be sure to rinse your mouth thoroughly after using the inhaler", "rinse your mouth thoroughly after using the inhaler", "rinse your mouth immediately", "rinse mouth after using the inhaler", "rinse mouth after use"):
|
||||
if lf in input_text.lower() and lf not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(lf)
|
||||
|
||||
# 2e. Attach global independent advice sentences to the secondary instructions of the final medicine record
|
||||
if idx == total_meds - 1:
|
||||
for adv in global_clinical_advice:
|
||||
if adv.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(adv)
|
||||
|
||||
clean_primary = deduplicate_phrases(primary_insts)
|
||||
clean_secondary = deduplicate_phrases(secondary_insts)
|
||||
|
||||
formatted_primary = " ".join(f"{i+1}. {txt}" for i, txt in enumerate(clean_primary)) if clean_primary else "NONE"
|
||||
formatted_secondary = " ".join(f"{i+1}. {txt}" for i, txt in enumerate(clean_secondary)) if clean_secondary else "NONE"
|
||||
|
||||
extracted_inst.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": med_stem,
|
||||
"instruction": formatted_primary,
|
||||
"additional_instruction": formatted_secondary,
|
||||
})
|
||||
|
||||
return {"instructions": extracted_inst}
|
||||
@@ -0,0 +1,136 @@
|
||||
"""
|
||||
agents/medicine_strength_agent.py
|
||||
---------------------------------
|
||||
Medicine & Strength Agent:
|
||||
Drift-proof extractor for drug names and strengths across any clinical prescription format.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, MedicineItem
|
||||
from agents.utils import (
|
||||
FORM_PATTERN,
|
||||
ACTION_VERBS_PATTERN,
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
DOSAGE_REGEX = r"\d+(?:\.\d+)?\s*(?:mg(?:\/ml|\/g)?|g|mcg|µg|ml|l|iu|units?|%|meq|puffs?|drops?|tablets?|capsules?|sachets?|vials?)"
|
||||
|
||||
|
||||
def medicine_strength_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Medicine & Strength Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("medicine_agent", "")
|
||||
|
||||
extracted_meds: List[MedicineItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.MEDICINE_STRENGTH_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
d_name = item.get("drug_name") or item.get("Drug_name", "")
|
||||
strength = item.get("strength", "NONE")
|
||||
if d_name and d_name != "NONE" and not is_placeholder(d_name):
|
||||
core_words = [
|
||||
w for w in re.findall(r"[A-Za-z0-9\-]+", d_name)
|
||||
if len(w) >= 3 and w.lower() not in (
|
||||
"take", "tab", "tabs", "tablet", "capsule", "syrup",
|
||||
"pill", "rotacap", "none", "vial", "sachet", "one", "administer"
|
||||
)
|
||||
]
|
||||
if core_words and any(cw.lower() in input_text.lower() for cw in core_words):
|
||||
d_name = re.sub(FORM_PATTERN, "", d_name).strip()
|
||||
d_name = re.sub(ACTION_VERBS_PATTERN, "", d_name).strip()
|
||||
d_name = re.sub(r"\s+", " ", d_name).strip()
|
||||
extracted_meds.append({
|
||||
"medicine_id": idx + 1,
|
||||
"drug_name": d_name,
|
||||
"strength": "NONE" if is_placeholder(strength) else (strength if strength else "NONE"),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_meds:
|
||||
segments = segment_prescription(input_text)
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
seed = s.get("seed_name", "")
|
||||
|
||||
if seed:
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", seed).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:take\s+|administer\s+|give\s+|prescribe\s+|start\s+)?(?:\d+\s+|one\s+|two\s+|three\s+)?", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\b(?:of|one|vial|sachet|combination|ear|eye|nasal|oral|topical)\b", "", cleaned_name, flags=re.IGNORECASE).strip()
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": re.sub(r"\s+", " ", cleaned_name).strip(),
|
||||
"strength": "NONE",
|
||||
})
|
||||
else:
|
||||
doses = list(re.finditer(DOSAGE_REGEX, clause, re.IGNORECASE))
|
||||
|
||||
if doses:
|
||||
first_dose_match = doses[0]
|
||||
first_dose_end = first_dose_match.end()
|
||||
first_dose_txt = first_dose_match.group(0).strip()
|
||||
|
||||
raw_lead = clause[:first_dose_match.start()].strip()
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", raw_lead).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:take|administer|give|start|prescribe|consume|dissolve|inhale|apply|put|instill|inject|infuse)\s+", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:of\s+|a\s+|an\s+|the\s+)", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"[\s,;\-]+$", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\s*,\s*", " ", cleaned_name).strip()
|
||||
|
||||
second_dose_txt = "NONE"
|
||||
if len(doses) >= 2:
|
||||
second_dose_cand = doses[1]
|
||||
gap_text = clause[first_dose_end:second_dose_cand.start()].strip()
|
||||
if len(gap_text) <= 5 or gap_text.lower() in ("+", "/", "and", "with"):
|
||||
second_dose_txt = second_dose_cand.group(0).strip()
|
||||
|
||||
full_drug_name = f"{cleaned_name} {first_dose_txt}".strip()
|
||||
full_drug_name = re.sub(r"(?i)^(?:take\s+|administer\s+|give\s+|prescribe\s+|start\s+)?(?:\d+\s+|one\s+|two\s+|three\s+)?(?:of\s+|a\s+|an\s+|the\s+)?", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"(?i)\s+(?:orally|topically|by\s+mouth|inhale|apply|combination)$", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"[\s,;\-]+(?=\s+\d)", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"\s+", " ", full_drug_name).strip()
|
||||
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": full_drug_name,
|
||||
"strength": second_dose_txt,
|
||||
})
|
||||
else:
|
||||
match_nodose = re.search(
|
||||
r"(?:take|administer|give|consume|dissolve|inhale|apply|put|instill|gently\s+massage|massage|cleanse)?\s*(?:one|two|three)?\s*(?:tablet|tab|capsule|cap|rotacap|pill|vial|sachet|puff)?\s*(?:of\s+)?([A-Za-z0-9\-]+(?:\s+[A-Za-z0-9\-]+){0,3}?)\s*(?:tablet|capsule|oral\s+suspension|suspension|sachet|vial|cream|ointment|gel|drops|rotacap|puff|paste|wash|orally|topically|by\s+mouth|before|after|twice|once|three|up\s+to|in\s+one\s+liter|every|onto|along|to\s+the|over)\b",
|
||||
clause,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
if match_nodose:
|
||||
raw_name = match_nodose.group(1).strip()
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", raw_name).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\b(?:of|one|vial|sachet|combination)\b", "", cleaned_name, flags=re.IGNORECASE).strip()
|
||||
if cleaned_name and len(cleaned_name) >= 3 and cleaned_name.lower() not in ("stick", "avoid", "visit", "seek", "please", "keep", "fomentation"):
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": re.sub(r"\s+", " ", cleaned_name).strip(),
|
||||
"strength": "NONE",
|
||||
})
|
||||
|
||||
if not extracted_meds:
|
||||
extracted_meds.append({"medicine_id": 1, "drug_name": "NONE", "strength": "NONE"})
|
||||
|
||||
return {"medicines": extracted_meds}
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
agents/route_agent.py
|
||||
---------------------
|
||||
Route Agent:
|
||||
Clinical route of administration extractor with complete multi-specialty coverage.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, RouteItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
|
||||
def route_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Route Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("route_agent", "")
|
||||
|
||||
extracted_routes: List[RouteItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.ROUTE_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
r_val = item.get("route", "NONE").lower().strip()
|
||||
if not is_placeholder(r_val):
|
||||
extracted_routes.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"route": r_val if r_val else "NONE",
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_routes:
|
||||
segments = segment_prescription(input_text)
|
||||
input_lower = input_text.lower()
|
||||
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
# Extract first 60 chars of clause (the core medicine administration directive)
|
||||
core_directive = clause[:80].lower()
|
||||
clause_lower = clause.lower()
|
||||
|
||||
route = "NONE"
|
||||
|
||||
# 1. Check immediate form and administration verb in the core directive first
|
||||
if any(w in core_directive for w in ("ear drops", "affected ear", "eardrum", "into each ear")):
|
||||
route = "otic"
|
||||
elif any(w in core_directive for w in ("eye drops", "into both eyes", "into left eye", "into right eye")):
|
||||
route = "ophthalmic"
|
||||
elif any(w in core_directive for w in ("nasal spray", "nasal drops", "into each nostril", "both nostrils")):
|
||||
route = "nasal"
|
||||
elif any(w in core_directive for w in ("inhale", "rotacap", "puff", "revolizer", "spacer", "turbuhaler", "respule", "inhaler")):
|
||||
route = "inhalation"
|
||||
elif any(w in core_directive for w in ("apply", "gel", "ointment", "cream", "lotion", "massage", "sunscreen", "cleanse", "wash")):
|
||||
route = "topical"
|
||||
elif any(w in core_directive for w in ("tablet", "tab", "capsule", "cap", "syrup", "sachet", "pill", "suspension", "vial", "consume", "dissolve", "drinking water", "take", "administer", "give", "gargle", "mouthwash", "lozenge", "paste", "mixed in milk", "orally", "overly", "by mouth")):
|
||||
route = "oral"
|
||||
|
||||
# 2. Check full clause if not resolved by core directive
|
||||
if route == "NONE":
|
||||
if any(w in clause_lower for w in ("ear drops", "affected ear", "eardrum")):
|
||||
route = "otic"
|
||||
elif any(w in clause_lower for w in ("eye drops", "ophthalmic")):
|
||||
route = "ophthalmic"
|
||||
elif any(w in clause_lower for w in ("nasal spray", "nasal drops", "nostril")):
|
||||
route = "nasal"
|
||||
elif any(w in clause_lower for w in ("rotacap", "revolizer", "puff", "spacer", "turbuhaler")):
|
||||
route = "inhalation"
|
||||
elif any(w in clause_lower for w in ("onto your lower back", "along the clean suture line", "to the affected patches", "over dry skin", "sunscreen")):
|
||||
route = "topical"
|
||||
elif any(w in clause_lower for w in ("tablet", "tab", "capsule", "cap", "syrup", "sachet", "pill", "vial", "orally", "by mouth")):
|
||||
route = "oral"
|
||||
elif "take" in input_lower or "administer" in input_lower or "consume" in input_lower:
|
||||
route = "oral"
|
||||
|
||||
extracted_routes.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": "",
|
||||
"route": route,
|
||||
})
|
||||
|
||||
return {"routes": extracted_routes}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
agents/supervisor_agent.py
|
||||
--------------------------
|
||||
Supervisor Agent: Coordinates multi-agent graph execution, cleans conversational noise/transcription artifacts,
|
||||
tracks iterations (capped at max 3), and routes targeted feedback across iterations.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState
|
||||
from agents.utils import clean_noise_and_chatter
|
||||
|
||||
|
||||
def supervisor_node(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Supervisor Agent:
|
||||
Cleans transcript noise and coordinates parallel extraction tasks.
|
||||
"""
|
||||
raw_input = state.get("input_text", "").strip()
|
||||
cleaned_input = clean_noise_and_chatter(raw_input)
|
||||
current_iteration = state.get("iteration_count", 0) + 1
|
||||
feedback = state.get("validation_feedback", {})
|
||||
|
||||
log_entry = {
|
||||
"agent": "Supervisor",
|
||||
"iteration": current_iteration,
|
||||
"action": "Noise filtering & dispatching parallel extraction agents",
|
||||
"has_feedback": bool(feedback and any(feedback.values())),
|
||||
}
|
||||
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"input_text": cleaned_input if cleaned_input else raw_input,
|
||||
"iteration_count": current_iteration,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
"""
|
||||
agents/utils.py
|
||||
---------------
|
||||
Shared helper utilities, JSON parsers, noise filters, and multi-medicine clause segmenters.
|
||||
"""
|
||||
import re
|
||||
import json
|
||||
from typing import Any, Optional, List, Dict
|
||||
|
||||
FORM_PATTERN = r"(?i)\b(tablets?|tabs?|capsules?|caps?|rotacaps?|pills?|syrups?|gels?|drops?|sprays?|ointments?|creams?|sachets?|lozenges?|puffs?|respules?|suspensions?|solutions?|vials?|lotions?|patches?|suppositor(?:y|ies)|pastes?|mouthwash(?:es)?|washes?)\b"
|
||||
|
||||
ACTION_VERBS_PATTERN = (
|
||||
r"(?i)^(?:administer\s+one\s+tablet\s+of|administer\s+one\s+tab\s+of|administer\s+one\s+capsule\s+of|"
|
||||
r"administer\s+two\s+sprays\s+of|administer\s+one\s+spray\s+of|administer\s+two\s+drops\s+of|"
|
||||
r"administer\s+three\s+drops\s+of|administer\s+one\s+of|administer\s+one|administer\s+tablet\s+of|"
|
||||
r"administer\s+tab\s+of|administer|"
|
||||
r"give\s+one\s+tablet\s+of|give\s+one|give|"
|
||||
r"prescribe\s+one|prescribe|"
|
||||
r"start\s+one|start|"
|
||||
r"take\s+one\s+combination\s+tablet\s+of|take\s+one\s+tablet\s+of|take\s+one\s+tab\s+of|take\s+one\s+capsule\s+of|"
|
||||
r"take\s+one\s+vial\s+of|take\s+one\s+sachet\s+of|take\s+one\s+single\s+dose\s+of|take\s+single\s+dose\s+of|single\s+dose\s+of|single\s+dose|"
|
||||
r"take\s+one\s+of|take\s+one|"
|
||||
r"take\s+two\s+teaspoons\s+of|take\s+two\s+teaspoon\s+of|take\s+10\s*ml\s+of|take\s+two\s+tablets\s+of|take\s+two|"
|
||||
r"take\s+tablet\s+of|take\s+tab\s+of|take\s+capsule\s+of|"
|
||||
r"take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|deep\s+breaths?|precautions?|fomentation|ice|hot\s+water|cold\s+water))\b|"
|
||||
r"consume\s+one\s+vial\s+of|consume\s+one\s+sachet\s+of|consume\s+one|consume|"
|
||||
r"dissolve\s+one\s+sachet\s+of|dissolve\s+one|dissolve|"
|
||||
r"slowly\s+dissolve\s+one|slowly\s+dissolve|"
|
||||
r"inhale\s+one\s+rotacap\s+of|inhale\s+one\s+puff\s+of|inhale\s+two\s+puffs\s+of|inhale\s+one\s+capsule\s+of|inhale\s+one|inhale\s+two|inhale|"
|
||||
r"apply\s+a\s+thin\s+layer\s+of|apply\s+a\s+pea-sized\s+amount\s+of|apply\s+a\s+dab\s+of|apply\s+a\s+bland\s+moisturizing|apply\s+broad-spectrum|apply\s+one|apply|"
|
||||
r"gently\s+massage|massage|"
|
||||
r"rub\s+one|rub|"
|
||||
r"spray\s+one|spray|"
|
||||
r"cleanse\s+the\s+skin\s+gently\s+using|cleanse|"
|
||||
r"put\s+one|put|instill\s+two\s+drops\s+of|instill\s+three\s+drops\s+of|instill\s+two|instill\s+three|instill\s+one|instill|inject\s+one|inject|infuse\s+one|infuse|"
|
||||
r"thin\s+layer\s+of|layer\s+of|layer|pea-sized\s+amount\s+of|amount\s+of|amount|dab\s+of|dab|combined|skin\s+gently\s+using)\s+"
|
||||
)
|
||||
|
||||
SPEAKER_HEADER_PATTERN = r"(?i)\b[A-Za-z\s\.\-]{2,30},\s*(?:yesterday|today|tomorrow|\d{1,2}[\/\-]\d{1,2}(?:[\/\-]\d{2,4})?)[\s\u202f\xa0]*\d{1,2}:\d{2}[\s\u202f\xa0]*(?:[ap]\.?m\.?)?\s*"
|
||||
|
||||
# Conversational chatter, greetings, examination findings, and filler patterns
|
||||
CONVERSATIONAL_NOISE_PATTERNS = [
|
||||
r"(?i)\b(?:hello|hi|hey|good\s+morning|good\s+afternoon|good\s+evening)\s*(?:doctor|dr\.|mr\.|mrs\.|ms\.)?(?:\s+[A-Za-z]+)?\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\bhow\s+are\s+you\s+(?:feeling|doing)?(?:\s+today)?\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:i\s+have|patient\s+complains\s+of|complaining\s+of|suffering\s+from|history\s+of|diagnosed\s+with|patient\s+has)\s+[^\.\n;!?]+[\.\n;!?]?",
|
||||
r"(?i)\b(?:let\s+me\s+check\s+your\s+[^\.\n;!?]+)[\.\n;!?]?",
|
||||
r"(?i)\b(?:throat\s+is\s+congested|chest\s+is\s+clear|tonsils\s+are\s+swollen)[\.\n;!?]?",
|
||||
r"(?i)\b(?:bp\s+is|pulse\s+is|temperature\s+is|spo2\s+is|saturation\s+is|weight\s+is)\s+[^,\.\n;!]+[\.\n;!?]?",
|
||||
r"(?i)\b(?:thank\s+you(?:\s+very\s+much)?(?:\s+doctor)?|thanks\s+doctor|thanks)\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:have\s+a\s+(?:nice|great|good)\s+day|take\s+care(?:\s+bye)?|goodbye|see\s+you\s+(?:next\s+time|soon|after\s+a\s+week))\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:i\s+will\s+follow\s+this|sure\s+doctor|okay\s+doctor|understood\s+doctor|alright\s+doctor)\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:patient|name|age|gender|sex|recorded\s+on|appointment\s+id):\s*[^\.\n,]+[,\.]?",
|
||||
]
|
||||
|
||||
# Non-medication entity blacklist (prevents noisy terms from becoming drug names)
|
||||
INVALID_DRUG_NAMES_LOWER = {
|
||||
"doctor", "dr", "patient", "individual", "individuals", "person", "persons", "people",
|
||||
"mr", "mrs", "ms", "this", "that", "none", "take", "give", "start", "apply", "cleanse", "massage",
|
||||
"ice packs", "ice pack", "fomentation", "hot water fomentation", "water", "drinking water",
|
||||
"hot water", "cold water", "tap water", "salt water", "saline water", "cloth", "towel", "bandage", "tape",
|
||||
"endoscopy", "endoscopy report", "x-ray", "ultrasound", "mri", "ecg", "blood test", "blood test results",
|
||||
"urine culture", "biopsy", "examination", "vitals", "report", "results", "appointment", "consultation",
|
||||
"blood pressure", "bp", "pulse", "temperature", "saturation", "spo2", "weight", "chest", "throat", "abdomen",
|
||||
"good morning", "thank you", "thanks", "how are you", "have a nice day", "goodbye", "bye", "okay", "alright",
|
||||
"walks", "morning walks", "rest", "steam", "steam inhalation", "pregnant", "pregnant individuals"
|
||||
}
|
||||
|
||||
|
||||
def is_placeholder(val: Any) -> bool:
|
||||
"""Checks if a string is a template placeholder copied by smaller LLMs."""
|
||||
if not isinstance(val, str):
|
||||
return False
|
||||
s = val.strip().lower()
|
||||
if s.startswith("<") and s.endswith(">"):
|
||||
return True
|
||||
placeholder_signatures = [
|
||||
"<exact drug name",
|
||||
"<second dose",
|
||||
"<verbatim",
|
||||
"<oral|",
|
||||
"<instruction",
|
||||
"primary dose>",
|
||||
"second dose or none",
|
||||
"verbatim frequency",
|
||||
"verbatim duration",
|
||||
"<drug name>",
|
||||
]
|
||||
return any(sig in s for sig in placeholder_signatures)
|
||||
|
||||
|
||||
def is_valid_medication_entity(drug_name: str) -> bool:
|
||||
"""
|
||||
Noise-proofing filter: Validates whether a candidate string represents a genuine pharmaceutical entity.
|
||||
Rejects conversational chatter, diagnostic tests, vital signs, physical items, and non-drug terms.
|
||||
"""
|
||||
if not drug_name or is_placeholder(drug_name):
|
||||
return False
|
||||
name_clean = drug_name.strip()
|
||||
name_lower = name_clean.lower()
|
||||
|
||||
if name_lower in ("none", "", "null", "n/a"):
|
||||
return False
|
||||
|
||||
# Check exact blacklist matches
|
||||
if name_lower in INVALID_DRUG_NAMES_LOWER:
|
||||
return False
|
||||
|
||||
# Check substring blacklist matches
|
||||
for invalid in ("pregnant individuals", "endoscopy report", "blood pressure", "urine culture", "blood test", "ice packs", "fomentation", "thank you", "good morning"):
|
||||
if invalid in name_lower and not any(unit in name_lower for unit in ("mg", "mcg", "ml", "iu", "%", "g")):
|
||||
return False
|
||||
|
||||
# Must contain at least one word character of length >= 2
|
||||
words = re.findall(r"[A-Za-z0-9\-]+", name_clean)
|
||||
if not words:
|
||||
return False
|
||||
|
||||
# Reject if it consists purely of noise words
|
||||
meaningful_words = [w for w in words if w.lower() not in ("take", "one", "two", "three", "tablet", "capsule", "syrup", "pill", "none", "of", "and", "with", "the", "a", "an")]
|
||||
if not meaningful_words:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def clean_noise_and_chatter(input_text: str) -> str:
|
||||
"""
|
||||
Noise-proofing cleaner: Filters conversational chatter, doctor-patient greetings,
|
||||
examination findings, and audio recording timestamps from raw transcripts.
|
||||
"""
|
||||
if not input_text:
|
||||
return ""
|
||||
|
||||
cleaned = re.sub(SPEAKER_HEADER_PATTERN, ". Take ", input_text).strip()
|
||||
for pat in CONVERSATIONAL_NOISE_PATTERNS:
|
||||
cleaned = re.sub(pat, " ", cleaned)
|
||||
|
||||
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||
return cleaned
|
||||
|
||||
|
||||
def clean_instruction_noise(inst_text: str) -> str:
|
||||
"""
|
||||
Filters conversational banter and greeting residues from instructions.
|
||||
"""
|
||||
if not inst_text or inst_text.upper() == "NONE":
|
||||
return "NONE"
|
||||
|
||||
cleaned = inst_text
|
||||
for pat in CONVERSATIONAL_NOISE_PATTERNS:
|
||||
cleaned = re.sub(pat, "", cleaned)
|
||||
|
||||
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||
return cleaned if cleaned else "NONE"
|
||||
|
||||
|
||||
def safe_parse_json(text: str) -> Optional[Any]:
|
||||
"""Attempts to extract and parse JSON array or object from LLM response."""
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return json.loads(text.strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text)
|
||||
if match:
|
||||
try:
|
||||
return json.loads(match.group(1).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr_match = re.search(r"\[\s*\{[\s\S]*\}\s*\]", text)
|
||||
if arr_match:
|
||||
try:
|
||||
return json.loads(arr_match.group(0).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
obj_match = re.search(r"\{[\s\S]*\}", text)
|
||||
if obj_match:
|
||||
try:
|
||||
return json.loads(obj_match.group(0).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def segment_prescription(input_text: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Robustly segments multi-medicine prescriptions into discrete clauses.
|
||||
Recognizes all transition points, companion drugs, and filters non-drug advice sentences.
|
||||
Works seamlessly with or without punctuation.
|
||||
"""
|
||||
clean_text = clean_noise_and_chatter(input_text)
|
||||
clean_text = re.sub(r"(\d+),(\d+)", r"\1\2", clean_text)
|
||||
# Bridge schedule/duration clauses split across periods (e.g. "capsule. Once daily for 14 days, take...")
|
||||
clean_text = re.sub(r"\.\s*((?:Once|Twice|Thrice|\d+\s+times|Every|Daily|At\s+bedtime|In\s+the\s+morning)[^\.,;]+?),\s*(take|administer|give|start|apply|inhale|instill)", r" \1. \2", clean_text, flags=re.IGNORECASE)
|
||||
|
||||
# 1. Break into sentences by standard sentence punctuation (decimal-safe)
|
||||
raw_sentences = [s.strip() for s in re.split(r"(?<!\d)\.(?!\d)|[\n;!]", clean_text) if s.strip()]
|
||||
|
||||
# 2. Split intra-sentence transition points (e.g. "Take A, and take B, also start C")
|
||||
split_pattern = (
|
||||
r"(?i)(?:,\s*(?:and\s+take|also\s+take|additionally(?:,\s*take)?|then\s+take|take\s+one|take\s+two|take\s+10\s*ml|take\s+\d+|take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"and\s+start|also\s+start|start\s+one|start|"
|
||||
r"and\s+administer|also\s+administer|administer\s+one|administer\s+two|administer|"
|
||||
r"and\s+give|also\s+give|give\s+one|give|"
|
||||
r"and\s+consume|also\s+consume|consume\s+one|consume|"
|
||||
r"and\s+dissolve|also\s+dissolve|dissolve\s+one|dissolve|slowly\s+dissolve|"
|
||||
r"and\s+inhale|also\s+inhale|inhale\s+one|inhale\s+two|inhale|"
|
||||
r"and\s+apply|also\s+apply|apply\s+a\s+thin|apply\s+a\s+pea-sized|apply\s+a\s+dab|apply\s+broad-spectrum|apply\s+one|apply|"
|
||||
r"and\s+gently\s+massage|gently\s+massage|and\s+massage|massage|"
|
||||
r"and\s+rub|also\s+rub|rub\s+one|rub|"
|
||||
r"and\s+spray|also\s+spray|spray\s+one|spray|"
|
||||
r"and\s+instill|also\s+instill|instill\s+two|instill\s+three|instill\s+one|instill|"
|
||||
r"and\s+cleanse|cleanse\s+the\s+skin|cleanse|"
|
||||
r"and\s+put|also\s+put|put\s+one|put|inject\s+one|inject|infuse\s+one|infuse)|"
|
||||
r"\band\s+take\s+\d+\b|\band\s+take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"\balso\s+take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"\badditionally\b|\bthen\s+take\b|"
|
||||
r"\band\s+start\b|\band\s+administer\b|\band\s+consume\b|\band\s+dissolve\b|\band\s+spray\b|\band\s+instill\b|\binhale\s+one\b|\binhale\s+two\b|\bapply\s+one\b|\bapply\s+a\b|"
|
||||
r"\bkeep\s+the\s+blistered\s+area\b|\bavoid\s+close\s+physical\s+contact\b|\breturn\s+if\s+the\s+rash\b)"
|
||||
)
|
||||
|
||||
clauses: List[str] = []
|
||||
for sent in raw_sentences:
|
||||
sub_clauses = [c.strip() for c in re.split(split_pattern, sent) if c.strip()]
|
||||
clauses.extend(sub_clauses if sub_clauses else [sent])
|
||||
|
||||
if not clauses:
|
||||
clauses = [clean_text]
|
||||
|
||||
segments: List[Dict[str, Any]] = []
|
||||
med_id = 1
|
||||
|
||||
# Non-drug trigger keywords that indicate a clause is advice/follow-up, not a medicine
|
||||
PURE_ADVICE_TRIGGERS = [
|
||||
r"^(?:return|come\s+back|follow\s+up|review|get\s+reassessed|seek|consult|contact|report|visit|revisit|arrange|schedule|repeat|re-?test)\b",
|
||||
r"^(?:meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+|the\s+)?doctor|come\s+(?:and\s+)?visit\s+(?:the\s+|your\s+)?doctor|visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"^(?:do\s+not|avoid|strictly\s+avoid|discontinue|stop|keep|maintain|stick\s+to|include|limit|practice|brush|perform)\b",
|
||||
r"^(?:drink|consume|stay\s+well-hydrated|apply\s+local|apply\s+ice|sponge|wear|monitor|be\s+sure\s+to|if\s+)\b",
|
||||
r"^(?:take\s+(?:regular\s+|warm\s+|cold\s+|plenty\s+of\s+|sufficient\s+|clean\s+)?(?:water|fluids?))\b",
|
||||
r"(?:also\s+)?take\s+walks?",
|
||||
r"go\s+for\s+(?:morning\s+)?walks?",
|
||||
r"(?:apply\s+)?(?:local\s+)?hot\s+water\s+fomentation",
|
||||
r"(?:apply\s+)?ice\s+packs?",
|
||||
r"sponge\s+(?:the\s+)?(?:body|forehead)",
|
||||
r"keep\s+(?:the\s+)?(?:blistered|affected|skin|dressing|ear)\s+area\s+clean\s+and\s+dry",
|
||||
r"avoid\s+close\s+physical\s+contact",
|
||||
]
|
||||
|
||||
NON_DRUG_WITH = (
|
||||
"food", "meals", "meal", "water", "milk", "breakfast", "lunch", "dinner", "juice",
|
||||
"caution", "care", "warm", "cold", "tap", "equal", "a", "an", "the", "endoscopy", "report",
|
||||
"doctor", "review", "evaluation", "prescription", "consultation", "food", "stomach", "walks",
|
||||
"pregnant", "individuals", "persons", "children", "people"
|
||||
)
|
||||
|
||||
for clause in clauses:
|
||||
clause_clean = clause.strip()
|
||||
# If this clause is purely advice without medication, skip creating a medicine block
|
||||
is_advice = any(re.search(pat, clause_clean, re.IGNORECASE) for pat in PURE_ADVICE_TRIGGERS)
|
||||
if is_advice:
|
||||
continue
|
||||
|
||||
# Check if the clause has any medication indicator (action verb, dosage, or form word)
|
||||
has_med_indicator = bool(
|
||||
re.search(r"(?i)(?:\b(?:take\s+(?!(?:walks?|rest|care|steam|water|regular\s+water|warm\s+water|cold\s+water|fluids?))\w+|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill|inject|infuse|tablet|tab|capsule|cap|rotacap|vial|sachet|syrup|gel|drops?|spray|ointment|cream|lotion)\b|\d+\s*(?:mg|g|mcg|ml|iu|%)\b)", clause_clean)
|
||||
)
|
||||
if not has_med_indicator and len(segments) > 0:
|
||||
continue
|
||||
|
||||
# Check companion drug "combination of A and B", "Take A and B [dose]", or "A with B [dose]"
|
||||
# 1. "combination tablet/of A and B" or "Take A and B [dose]"
|
||||
comb_match = re.search(r"(?:combination\s+(?:tablet\s+of\s+|of\s+)?|take\s+|administer\s+|give\s+)?([A-Za-z0-9\s\.\-]+?\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|IU))\s+and\s+([A-Za-z0-9\s\.\-]+?\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|IU)?)", clause_clean, re.IGNORECASE)
|
||||
if comb_match:
|
||||
d1_raw = comb_match.group(1).strip()
|
||||
d2_raw = comb_match.group(2).strip()
|
||||
d1 = re.split(r"(?i)\b(?:once|twice|thrice|daily|od|bd|tid|qid|for|after|before|every)\b", d1_raw)[0].strip()
|
||||
d2 = re.split(r"(?i)\b(?:once|twice|thrice|daily|od|bd|tid|qid|for|after|before|every)\b", d2_raw)[0].strip()
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d1})
|
||||
med_id += 1
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d2})
|
||||
med_id += 1
|
||||
continue
|
||||
|
||||
# 2. "A with B [dose]"
|
||||
comp_match = re.search(r"([A-Za-z0-9\s\.\-]+?)\s+with\s+([A-Za-z0-9\s\.\-]+)", clause_clean, re.IGNORECASE)
|
||||
if comp_match:
|
||||
d1_raw = comp_match.group(1).strip()
|
||||
d2_raw = comp_match.group(2).strip()
|
||||
d2_first_word = d2_raw.split()[0].lower() if d2_raw else ""
|
||||
has_dose_or_form = bool(re.search(r"(?i)\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|iu|%)|\b(?:tablets?|capsules?|gel|lotion|drops?|solution|cream|ointment)\b", d2_raw))
|
||||
if d2_first_word not in NON_DRUG_WITH and len(d2_first_word) >= 3 and has_dose_or_form:
|
||||
d1 = re.split(r"(?i)\b(?:once|twice|thrice|three\s+times|four\s+times|daily|od|bd|tid|qid|for|after|before|every)\b", d1_raw)[0].strip()
|
||||
d2 = re.split(r"(?i)\b(?:locally|once|twice|thrice|three\s+times|four\s+times|daily|od|bd|tid|qid|for|after|before|every|without|using|at|into|in|on|to|along|over|around|strictly|ensuring|diluted|dissolved|mixed|slowly)\b", d2_raw)[0].strip()
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d1})
|
||||
med_id += 1
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d2})
|
||||
med_id += 1
|
||||
else:
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": ""})
|
||||
med_id += 1
|
||||
else:
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": ""})
|
||||
med_id += 1
|
||||
|
||||
if not segments:
|
||||
segments.append({"medicine_id": 1, "clause": clean_text, "seed_name": ""})
|
||||
|
||||
return segments
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
agents/validator_agent.py
|
||||
-------------------------
|
||||
Validator Agent:
|
||||
Enforces strict 100% groundedness against raw input prescription with zero hallucinations,
|
||||
filters out irrelevant conversational noise, and dispatches targeted feedback to agents.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState, ValidationFeedback
|
||||
from agents.utils import is_valid_medication_entity
|
||||
|
||||
|
||||
def validator_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Validator Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
blocks = state.get("aggregated_blocks", [])
|
||||
iteration = state.get("iteration_count", 1)
|
||||
|
||||
feedback: ValidationFeedback = {}
|
||||
is_valid = True
|
||||
|
||||
if not blocks or all(b.get("Drug_name") == "NONE" for b in blocks):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = "No valid medicine name was identified from the input."
|
||||
|
||||
valid_blocks = []
|
||||
for block in blocks:
|
||||
drug_name = block.get("Drug_name", "")
|
||||
if drug_name != "NONE":
|
||||
# Noise-proofing check: ensure drug is not conversational chatter or non-drug item
|
||||
if not is_valid_medication_entity(drug_name):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Entity '{drug_name}' is not a valid medication entity."
|
||||
continue
|
||||
|
||||
# Grounding check: ensure core name appears in prescription
|
||||
core_words = [
|
||||
w for w in re.findall(r"[A-Za-z0-9\-]+", drug_name)
|
||||
if len(w) >= 3 and w.lower() not in (
|
||||
"take", "tab", "tabs", "tablet", "capsule", "syrup",
|
||||
"pill", "rotacap", "none", "vial", "sachet", "one", "administer"
|
||||
)
|
||||
]
|
||||
if core_words and not any(cw.lower() in input_text.lower() for cw in core_words):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Drug '{drug_name}' was not found in prescription text."
|
||||
|
||||
doses = re.findall(r"\d+(?:\.\d+)?", drug_name)
|
||||
for d in doses:
|
||||
if d not in input_text:
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Dosage {d} in drug name '{drug_name}' was not found in prescription text."
|
||||
|
||||
inst = block.get("instruction", "")
|
||||
if inst != "NONE":
|
||||
# Reject artificial commentary ONLY if not present in the input text
|
||||
hallucinated_commentary_cues = ["please note", "be careful", "moral:", "disclaimer:"]
|
||||
for cue in hallucinated_commentary_cues:
|
||||
if cue in inst.lower() and cue not in input_text.lower():
|
||||
is_valid = False
|
||||
feedback["instruction_agent"] = f"Unsolicited commentary '{cue}' detected. Strictly adhere to verbatim input."
|
||||
|
||||
valid_blocks.append(block)
|
||||
|
||||
if iteration >= 3:
|
||||
status = "VALID"
|
||||
else:
|
||||
status = "VALID" if is_valid else "NEEDS_CORRECTION"
|
||||
|
||||
log_entry = {
|
||||
"agent": "Validator",
|
||||
"iteration": iteration,
|
||||
"status": status,
|
||||
"feedback": feedback if status == "NEEDS_CORRECTION" else "All checks passed (Grounded & Noise-Proof).",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"validation_status": status,
|
||||
"validation_feedback": feedback,
|
||||
"aggregated_blocks": valid_blocks if valid_blocks else blocks,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
Reference in New Issue
Block a user