feat: initial commit of Agentic ICD-10-CM Autonomous Code Matcher with 10-node LangGraph pipeline, deterministic guardrails, and professional documentation
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
"""Agent exports."""
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.agents.classifier import (
|
||||
ClassificationAgent,
|
||||
ContextAndRelevanceAgent,
|
||||
PrimarySecondaryClassifier,
|
||||
)
|
||||
from medical_coding.agents.extractor import (
|
||||
ClinicalExtractionAgent,
|
||||
DiagnosisExtractionAgent,
|
||||
)
|
||||
from medical_coding.agents.parser import ExtractionParser
|
||||
from medical_coding.agents.ranker import CandidateRankingAgent
|
||||
|
||||
__all__ = [
|
||||
"BaseAgent",
|
||||
"CandidateRankingAgent",
|
||||
"ClassificationAgent",
|
||||
"ClinicalExtractionAgent",
|
||||
"ContextAndRelevanceAgent",
|
||||
"DiagnosisExtractionAgent",
|
||||
"ExtractionParser",
|
||||
"PrimarySecondaryClassifier",
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Base agent interface for local LLM-driven clinical reasoning."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
|
||||
|
||||
class BaseAgent(ABC):
|
||||
"""Abstract base class for modular clinical reasoning agents."""
|
||||
|
||||
def __init__(self, llm: BaseLocalLLM) -> None:
|
||||
self.llm = llm
|
||||
|
||||
@abstractmethod
|
||||
def run(self, **kwargs: Any) -> Any:
|
||||
"""Execute agent reasoning step."""
|
||||
pass
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,336 @@
|
||||
"""Clinical Information Extraction Agent extracting structured conditions with verbatim evidence grounding."""
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.agents.parser import ExtractionParser
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.pdf.models import ClinicalPDFDocument
|
||||
from medical_coding.prompts.extraction import (
|
||||
CLINICAL_EXTRACTION_RETRY_TEMPLATE,
|
||||
CLINICAL_EXTRACTION_SYSTEM_PROMPT,
|
||||
CLINICAL_EXTRACTION_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClinicalExtractionResult,
|
||||
EvidenceSnippet,
|
||||
ExtractedClinicalCondition,
|
||||
ExtractedDiagnosis,
|
||||
TextSpan,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ClinicalExtractionAgent(BaseAgent):
|
||||
"""Extracts candidate medical conditions, certainty, temporality, and evidence without assigning ICD codes.
|
||||
|
||||
ARCHITECTURAL PRINCIPLES:
|
||||
1. NEVER generates or invents ICD codes.
|
||||
2. Every condition MUST have verbatim documentary evidence.
|
||||
3. Reconstructs structured context (CONFIRMED, SUSPECTED, POSSIBLE, RULED_OUT, HISTORICAL, RESOLVED, CURRENT).
|
||||
4. Handles contradictory mentions and past medical history appropriately.
|
||||
5. Robust parser with retry policy for local quantized LLMs.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm: BaseLocalLLM | LocalGPT4AllLangChainLLM,
|
||||
max_retries: int = 2,
|
||||
parser: ExtractionParser | None = None,
|
||||
) -> None:
|
||||
super().__init__(llm) # type: ignore[arg-type]
|
||||
self.max_retries = max_retries
|
||||
self.parser = parser or ExtractionParser()
|
||||
|
||||
def _generate(self, prompt: str) -> str:
|
||||
"""Call LLM synchronously across either BaseLocalLLM or LangChain LLM interface."""
|
||||
if hasattr(self.llm, "invoke"):
|
||||
return str(self.llm.invoke(prompt))
|
||||
if hasattr(self.llm, "generate"):
|
||||
return self.llm.generate(prompt)
|
||||
raise TypeError(f"Unsupported LLM instance type: {type(self.llm)}")
|
||||
|
||||
async def _generate_async(self, prompt: str) -> str:
|
||||
"""Call LLM asynchronously across either LangChain LLM or async lifecycle manager."""
|
||||
if hasattr(self.llm, "ainvoke"):
|
||||
res = await self.llm.ainvoke(prompt)
|
||||
return str(res)
|
||||
if hasattr(self.llm, "generate_async"):
|
||||
return await self.llm.generate_async(prompt)
|
||||
# Fallback to sync in thread
|
||||
import asyncio
|
||||
|
||||
return await asyncio.to_thread(self._generate, prompt)
|
||||
|
||||
def extract_clinical_conditions(
|
||||
self,
|
||||
document: ClinicalPDFDocument | str,
|
||||
doc_id: str | None = None,
|
||||
) -> ClinicalExtractionResult:
|
||||
"""Extract structured clinical conditions from a document synchronously.
|
||||
|
||||
Args:
|
||||
document: ClinicalPDFDocument instance or raw clinical text.
|
||||
doc_id: Optional document identifier.
|
||||
|
||||
Returns:
|
||||
ClinicalExtractionResult containing validated ExtractedClinicalCondition items.
|
||||
"""
|
||||
clinical_doc: ClinicalPDFDocument | None = None
|
||||
if isinstance(document, ClinicalPDFDocument):
|
||||
clinical_doc = document
|
||||
document_id = document.document_id
|
||||
# Send targeted clinical sections rather than raw entire document
|
||||
text_to_analyze = document.get_coding_text()
|
||||
full_text = document.full_normalized_text
|
||||
else:
|
||||
document_id = doc_id or str(uuid4())
|
||||
text_to_analyze = str(document).strip()
|
||||
full_text = text_to_analyze
|
||||
|
||||
if not text_to_analyze:
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=[],
|
||||
extraction_notes=["Input document text was empty."],
|
||||
repair_applied=False,
|
||||
)
|
||||
|
||||
# 1. Format initial extraction prompt
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_USER_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
logger.info("Executing clinical condition extraction for doc_id=%s...", document_id)
|
||||
raw_output = ""
|
||||
conditions: list[ExtractedClinicalCondition] = []
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
raw_output = self._generate(prompt)
|
||||
conditions, notes, repaired = self.parser.parse_and_validate(
|
||||
raw_llm_output=raw_output,
|
||||
document_text=full_text,
|
||||
clinical_doc=clinical_doc,
|
||||
)
|
||||
audit_notes.extend(notes)
|
||||
if repaired:
|
||||
repair_applied = True
|
||||
|
||||
if conditions or not text_to_analyze:
|
||||
# Successfully parsed conditions
|
||||
break
|
||||
|
||||
logger.warning(
|
||||
"Extraction attempt %d for doc %s produced 0 validated conditions. Retrying...",
|
||||
attempt + 1,
|
||||
document_id,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Extraction error during attempt %d: %s", attempt + 1, exc)
|
||||
audit_notes.append(f"Attempt #{attempt + 1} error: {exc}")
|
||||
|
||||
# Prepare retry prompt
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_RETRY_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
# 2. Resolve contradictory mentions & enforce past medical history rules
|
||||
resolved_conditions = self._reconcile_clinical_mentions(conditions)
|
||||
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=resolved_conditions,
|
||||
extraction_notes=audit_notes,
|
||||
repair_applied=repair_applied,
|
||||
raw_response=raw_output,
|
||||
)
|
||||
|
||||
async def extract_clinical_conditions_async(
|
||||
self,
|
||||
document: ClinicalPDFDocument | str,
|
||||
doc_id: str | None = None,
|
||||
) -> ClinicalExtractionResult:
|
||||
"""Asynchronously extract structured clinical conditions."""
|
||||
clinical_doc: ClinicalPDFDocument | None = None
|
||||
if isinstance(document, ClinicalPDFDocument):
|
||||
clinical_doc = document
|
||||
document_id = document.document_id
|
||||
text_to_analyze = document.get_coding_text()
|
||||
full_text = document.full_normalized_text
|
||||
else:
|
||||
document_id = doc_id or str(uuid4())
|
||||
text_to_analyze = str(document).strip()
|
||||
full_text = text_to_analyze
|
||||
|
||||
if not text_to_analyze:
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=[],
|
||||
extraction_notes=["Input document text was empty."],
|
||||
repair_applied=False,
|
||||
)
|
||||
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_USER_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
logger.info("Executing async clinical extraction for doc_id=%s...", document_id)
|
||||
raw_output = ""
|
||||
conditions: list[ExtractedClinicalCondition] = []
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
raw_output = await self._generate_async(prompt)
|
||||
conditions, notes, repaired = self.parser.parse_and_validate(
|
||||
raw_llm_output=raw_output,
|
||||
document_text=full_text,
|
||||
clinical_doc=clinical_doc,
|
||||
)
|
||||
audit_notes.extend(notes)
|
||||
if repaired:
|
||||
repair_applied = True
|
||||
|
||||
if conditions or not text_to_analyze:
|
||||
break
|
||||
except Exception as exc:
|
||||
audit_notes.append(f"Async attempt #{attempt + 1} error: {exc}")
|
||||
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_RETRY_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
resolved_conditions = self._reconcile_clinical_mentions(conditions)
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=resolved_conditions,
|
||||
extraction_notes=audit_notes,
|
||||
repair_applied=repair_applied,
|
||||
raw_response=raw_output,
|
||||
)
|
||||
|
||||
def _reconcile_clinical_mentions(
|
||||
self,
|
||||
conditions: list[ExtractedClinicalCondition],
|
||||
) -> list[ExtractedClinicalCondition]:
|
||||
"""Reconcile multiple or contradictory mentions of the same clinical condition.
|
||||
|
||||
Rules:
|
||||
1. If a condition is suspected initially but documented as RULED_OUT later,
|
||||
the definitive RULED_OUT certainty takes precedence.
|
||||
2. If a condition is ONLY mentioned in PAST_MEDICAL_HISTORY, enforce HISTORICAL temporality.
|
||||
3. If a condition is confirmed in DISCHARGE_DIAGNOSES, enforce CURRENT temporality (unless explicitly resolved).
|
||||
"""
|
||||
if not conditions:
|
||||
return []
|
||||
|
||||
# Group by normalized description
|
||||
by_concept: dict[str, list[ExtractedClinicalCondition]] = {}
|
||||
for c in conditions:
|
||||
key = c.normalized_description.lower().strip()
|
||||
by_concept.setdefault(key, []).append(c)
|
||||
|
||||
reconciled: list[ExtractedClinicalCondition] = []
|
||||
for _, items in by_concept.items():
|
||||
if len(items) == 1:
|
||||
item = items[0]
|
||||
# Enforce PMH rule: if only in PMH, must be HISTORICAL
|
||||
if "PAST" in item.section.upper() or "PMH" in item.section.upper():
|
||||
item.temporality = Temporality.HISTORICAL
|
||||
if item.status == ConditionStatus.ACUTE:
|
||||
item.status = ConditionStatus.CHRONIC
|
||||
reconciled.append(item)
|
||||
continue
|
||||
|
||||
# Multiple mentions exist (e.g. suspected in HPI, confirmed or ruled out in Discharge Diagnoses)
|
||||
has_ruled_out = any(it.certainty == Certainty.RULED_OUT for it in items)
|
||||
has_discharge_diag = any("DISCHARGE" in it.section.upper() for it in items)
|
||||
|
||||
if has_ruled_out:
|
||||
# Definitive exclusion overrides suspected/possible
|
||||
ruled_out_item = next(it for it in items if it.certainty == Certainty.RULED_OUT)
|
||||
ruled_out_item.status = ConditionStatus.RESOLVED
|
||||
ruled_out_item.negation = NegationStatus.NEGATED
|
||||
reconciled.append(ruled_out_item)
|
||||
elif has_discharge_diag:
|
||||
# Discharge diagnosis is authoritative
|
||||
dd_item = next(it for it in items if "DISCHARGE" in it.section.upper())
|
||||
dd_item.temporality = Temporality.CURRENT
|
||||
reconciled.append(dd_item)
|
||||
else:
|
||||
# Keep the mention with highest certainty
|
||||
sorted_items = sorted(
|
||||
items,
|
||||
key=lambda x: (
|
||||
1 if x.certainty == Certainty.CONFIRMED else 0,
|
||||
1 if x.temporality == Temporality.CURRENT else 0,
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
reconciled.append(sorted_items[0])
|
||||
|
||||
return reconciled
|
||||
|
||||
# Backwards-compatibility adapter for existing LangGraph nodes
|
||||
def extract(self, clinical_text: str) -> list[ExtractedDiagnosis]:
|
||||
"""Legacy interface adapting ExtractedClinicalCondition to ExtractedDiagnosis."""
|
||||
result = self.extract_clinical_conditions(clinical_text)
|
||||
diagnoses: list[ExtractedDiagnosis] = []
|
||||
for c in result.conditions:
|
||||
# Only include affirmative, non-ruled-out conditions
|
||||
if c.certainty == Certainty.RULED_OUT or c.negation == NegationStatus.NEGATED:
|
||||
continue
|
||||
|
||||
span = None
|
||||
if (
|
||||
c.evidence_location.start_char is not None
|
||||
and c.evidence_location.end_char is not None
|
||||
):
|
||||
span = TextSpan(
|
||||
start_char=c.evidence_location.start_char,
|
||||
end_char=c.evidence_location.end_char,
|
||||
text=c.evidence_text,
|
||||
page_number=c.evidence_location.page_number,
|
||||
)
|
||||
|
||||
snippet = EvidenceSnippet(
|
||||
quote=c.evidence_text,
|
||||
span=span,
|
||||
source_section=c.section,
|
||||
)
|
||||
|
||||
diag = ExtractedDiagnosis(
|
||||
diagnosis_id=c.condition_id,
|
||||
raw_term=c.normalized_description,
|
||||
evidence=snippet,
|
||||
extraction_confidence=c.confidence_score,
|
||||
)
|
||||
diagnoses.append(diag)
|
||||
|
||||
return diagnoses
|
||||
|
||||
def run(self, **kwargs: Any) -> list[ExtractedDiagnosis]:
|
||||
text = kwargs.get("clinical_text", "")
|
||||
return self.extract(text)
|
||||
|
||||
|
||||
# Backwards compatibility alias
|
||||
DiagnosisExtractionAgent = ClinicalExtractionAgent
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Robust JSON parser, clinical enum normalizer, and evidence-grounding validator for local LLM outputs."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.pdf.models import ClinicalPDFDocument
|
||||
from medical_coding.schemas.clinical import (
|
||||
EvidenceLocation,
|
||||
ExtractedClinicalCondition,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ClinicalEntityType,
|
||||
ConditionStatus,
|
||||
Laterality,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ExtractionParser:
|
||||
"""Parses and repairs structured extraction outputs from local LLMs.
|
||||
|
||||
Guarantees:
|
||||
1. Robust JSON extraction across markdown wrappers and conversational noise.
|
||||
2. Case-insensitive enum normalization with clinical synonym mapping.
|
||||
3. Strict evidence grounding: checks that evidence_text exists verbatim in the source document.
|
||||
4. Automatic resolution of character offsets, sections, and page numbers from documentary text.
|
||||
5. Zero hallucination: drops candidate conditions if evidence is completely absent from the text.
|
||||
"""
|
||||
|
||||
def parse_and_validate(
|
||||
self,
|
||||
raw_llm_output: str,
|
||||
document_text: str,
|
||||
clinical_doc: ClinicalPDFDocument | None = None,
|
||||
) -> tuple[list[ExtractedClinicalCondition], list[str], bool]:
|
||||
"""Parse raw LLM response into validated ExtractedClinicalCondition models.
|
||||
|
||||
Args:
|
||||
raw_llm_output: Unprocessed text emitted by the LLM.
|
||||
document_text: The source clinical text the LLM analyzed.
|
||||
clinical_doc: Optional structured ClinicalPDFDocument for exact page/section mapping.
|
||||
|
||||
Returns:
|
||||
(validated_conditions, audit_notes, repair_applied)
|
||||
"""
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
if not raw_llm_output or not raw_llm_output.strip():
|
||||
audit_notes.append("Raw LLM response was empty.")
|
||||
return [], audit_notes, False
|
||||
|
||||
# 1. Clean markdown code fences and extract JSON substring
|
||||
cleaned_text = self._strip_markdown_and_extract_json(raw_llm_output)
|
||||
if cleaned_text != raw_llm_output:
|
||||
repair_applied = True
|
||||
|
||||
parsed_json: Any = None
|
||||
try:
|
||||
parsed_json = json.loads(cleaned_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.warning(
|
||||
"Initial JSON parse failed: %s. Applying syntax repair heuristics...", exc
|
||||
)
|
||||
repaired_text = self._repair_json_syntax(cleaned_text)
|
||||
try:
|
||||
parsed_json = json.loads(repaired_text)
|
||||
repair_applied = True
|
||||
audit_notes.append("Applied syntax repair to malformed LLM JSON.")
|
||||
except Exception as repair_exc:
|
||||
logger.error("JSON repair heuristics failed: %s", repair_exc)
|
||||
audit_notes.append(f"Failed to parse LLM output as JSON: {exc}")
|
||||
return [], audit_notes, repair_applied
|
||||
|
||||
if not isinstance(parsed_json, list):
|
||||
if (
|
||||
isinstance(parsed_json, dict)
|
||||
and "conditions" in parsed_json
|
||||
and isinstance(parsed_json["conditions"], list)
|
||||
):
|
||||
parsed_json = parsed_json["conditions"]
|
||||
elif isinstance(parsed_json, dict):
|
||||
parsed_json = [parsed_json]
|
||||
else:
|
||||
audit_notes.append("Parsed JSON was not a list of candidate conditions.")
|
||||
return [], audit_notes, repair_applied
|
||||
|
||||
# 2. Validate, ground, and normalize each condition item
|
||||
validated_conditions: list[ExtractedClinicalCondition] = []
|
||||
norm_source = self._normalize_for_matching(document_text)
|
||||
|
||||
for idx, item in enumerate(parsed_json):
|
||||
if not isinstance(item, dict):
|
||||
audit_notes.append(f"Skipping non-dict condition at index {idx}.")
|
||||
continue
|
||||
|
||||
# Ensure minimum required fields exist
|
||||
mention = str(item.get("original_mention") or item.get("raw_term") or "").strip()
|
||||
evidence = str(item.get("evidence_text") or item.get("evidence_quote") or "").strip()
|
||||
|
||||
if not mention:
|
||||
audit_notes.append(f"Item #{idx} missing original_mention; discarded.")
|
||||
continue
|
||||
|
||||
# CRITICAL RULE: Every diagnosis must have evidence
|
||||
if not evidence:
|
||||
audit_notes.append(f"Item '{mention}' discarded: No evidence_text provided by LLM.")
|
||||
continue
|
||||
|
||||
# Check evidence grounding in source document
|
||||
span_found = self._locate_evidence_in_text(evidence, document_text, norm_source)
|
||||
if span_found is None:
|
||||
# Evidence could not be located in document
|
||||
audit_notes.append(
|
||||
f"Item '{mention}' discarded: evidence quote '{evidence[:60]}...' not found in source document."
|
||||
)
|
||||
continue
|
||||
|
||||
start_char, end_char = span_found
|
||||
|
||||
# Resolve page number and section
|
||||
page_num, sec_name = self._resolve_location_metadata(
|
||||
start_char=start_char,
|
||||
clinical_doc=clinical_doc,
|
||||
claimed_section=item.get("section"),
|
||||
)
|
||||
|
||||
# Map enums safely
|
||||
certainty = self._normalize_certainty(item.get("certainty"))
|
||||
temporality = self._normalize_temporality(item.get("temporality"))
|
||||
status = self._normalize_status(item.get("status"), temporality, certainty)
|
||||
negation = self._normalize_negation(item.get("negation"))
|
||||
laterality = self._normalize_laterality(item.get("laterality"))
|
||||
entity_type = self._normalize_entity_type(item.get("entity_type"))
|
||||
|
||||
norm_desc = str(item.get("normalized_description") or mention).strip()
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
original_mention=mention,
|
||||
normalized_description=norm_desc,
|
||||
entity_type=entity_type,
|
||||
evidence_text=evidence,
|
||||
evidence_location=EvidenceLocation(
|
||||
section=sec_name,
|
||||
page_number=page_num,
|
||||
start_char=start_char,
|
||||
end_char=end_char,
|
||||
),
|
||||
status=status,
|
||||
certainty=certainty,
|
||||
temporality=temporality,
|
||||
negation=negation,
|
||||
anatomical_site=item.get("anatomical_site") or None,
|
||||
laterality=laterality,
|
||||
section=sec_name,
|
||||
treatment_evidence=item.get("treatment_evidence") or None,
|
||||
confidence_score=float(item.get("confidence_score", 1.0)),
|
||||
)
|
||||
|
||||
validated_conditions.append(condition)
|
||||
|
||||
audit_notes.append(
|
||||
f"Successfully extracted and validated {len(validated_conditions)} conditions."
|
||||
)
|
||||
return validated_conditions, audit_notes, repair_applied
|
||||
|
||||
def _strip_markdown_and_extract_json(self, text: str) -> str:
|
||||
"""Strip markdown fences, leading explanations, and isolate the JSON array."""
|
||||
cleaned = text.strip()
|
||||
|
||||
# Handle ```json ... ``` or ``` ... ```
|
||||
if "```" in cleaned:
|
||||
match = re.search(r"```(?:json)?\s*(\[.*?\])\s*```", cleaned, re.DOTALL)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
# If no closing block or opening block, strip ``` lines
|
||||
cleaned = re.sub(r"```(?:json)?", "", cleaned).replace("```", "").strip()
|
||||
|
||||
# Isolate substring starting at first '[' and ending at last ']'
|
||||
start_idx = cleaned.find("[")
|
||||
end_idx = cleaned.rfind("]")
|
||||
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
|
||||
return cleaned[start_idx : end_idx + 1].strip()
|
||||
|
||||
return cleaned
|
||||
|
||||
def _repair_json_syntax(self, text: str) -> str:
|
||||
"""Apply heuristics to repair common LLM JSON syntax errors without hallucinating facts."""
|
||||
repaired = text
|
||||
|
||||
# Replace single quotes with double quotes around JSON keys and string values
|
||||
# e.g. {'key': 'value'} -> {"key": "value"}
|
||||
repaired = re.sub(r"(?<=[\{\s,\[])'([a-zA-Z0-9_\s\-]+)'(?=\s*:)", r'"\1"', repaired)
|
||||
repaired = re.sub(r":\s*'([^']*)'", r': "\1"', repaired)
|
||||
|
||||
# Remove trailing commas before closing braces/brackets: e.g. , ] -> ] and , } -> }
|
||||
repaired = re.sub(r",\s*([\]\}])", r"\1", repaired)
|
||||
|
||||
# Replace invalid unquoted literals or None -> null
|
||||
repaired = re.sub(r"\bNone\b", "null", repaired)
|
||||
repaired = re.sub(r"\bTrue\b", "true", repaired)
|
||||
repaired = re.sub(r"\bFalse\b", "false", repaired)
|
||||
|
||||
return repaired
|
||||
|
||||
def _normalize_for_matching(self, text: str) -> str:
|
||||
"""Normalize whitespace and case for relaxed quote matching."""
|
||||
return re.sub(r"\s+", " ", text).strip().lower()
|
||||
|
||||
def _locate_evidence_in_text(
|
||||
self,
|
||||
quote: str,
|
||||
original_text: str,
|
||||
norm_source: str,
|
||||
) -> tuple[int, int] | None:
|
||||
"""Verify quote exists in original text and return exact start/end character offsets."""
|
||||
if not quote:
|
||||
return None
|
||||
|
||||
# 1. Exact verbatim match
|
||||
start = original_text.find(quote)
|
||||
if start != -1:
|
||||
return start, start + len(quote)
|
||||
|
||||
# 2. Case-insensitive exact match
|
||||
lower_orig = original_text.lower()
|
||||
lower_quote = quote.lower()
|
||||
start = lower_orig.find(lower_quote)
|
||||
if start != -1:
|
||||
return start, start + len(quote)
|
||||
|
||||
# 3. Whitespace-normalized match
|
||||
norm_quote = self._normalize_for_matching(quote)
|
||||
start_norm = norm_source.find(norm_quote)
|
||||
if start_norm != -1:
|
||||
# Estimate reasonable span in original text
|
||||
approx_start = max(0, start_norm)
|
||||
approx_end = min(len(original_text), approx_start + len(quote) + 10)
|
||||
return approx_start, approx_end
|
||||
|
||||
return None
|
||||
|
||||
def _resolve_location_metadata(
|
||||
self,
|
||||
start_char: int,
|
||||
clinical_doc: ClinicalPDFDocument | None,
|
||||
claimed_section: str | None,
|
||||
) -> tuple[int, str]:
|
||||
"""Resolve page number and section name from clinical document offsets."""
|
||||
page_num = 1
|
||||
sec_name = str(claimed_section or "CLINICAL_DOCUMENT").upper().strip()
|
||||
|
||||
if clinical_doc is not None:
|
||||
page_num = clinical_doc.find_page_number_for_char(start_char)
|
||||
# Find matching section containing this character
|
||||
for s in clinical_doc.sections:
|
||||
if s.start_char <= start_char <= s.end_char:
|
||||
sec_name = s.section_type
|
||||
break
|
||||
|
||||
return page_num, sec_name
|
||||
|
||||
def _normalize_certainty(self, val: Any) -> Certainty:
|
||||
"""Map certainty strings to standardized Certainty enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "RULE" in s or "EXCLUD" in s or "DENI" in s:
|
||||
return Certainty.RULED_OUT
|
||||
if "SUSPECT" in s or "PROBAB" in s:
|
||||
return Certainty.SUSPECTED
|
||||
if "POSSIB" in s or "POTENTIAL" in s or "DIFFERENTIAL" in s:
|
||||
return Certainty.POSSIBLE
|
||||
if "CONFIRM" in s or "DEFINIT" in s or "POSITIVE" in s or "ACTIVE" in s:
|
||||
return Certainty.CONFIRMED
|
||||
return Certainty.CONFIRMED if not s else Certainty.UNKNOWN
|
||||
|
||||
def _normalize_temporality(self, val: Any) -> Temporality:
|
||||
"""Map temporality strings to standardized Temporality enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "RESOLV" in s or "CURED" in s:
|
||||
return Temporality.RESOLVED
|
||||
if "HISTOR" in s or "PAST" in s or "PMH" in s or "PRIOR" in s:
|
||||
return Temporality.HISTORICAL
|
||||
if "CURRENT" in s or "PRESENT" in s or "ACTIVE" in s or "ADMISSION" in s:
|
||||
return Temporality.CURRENT
|
||||
if "FAMILY" in s:
|
||||
return Temporality.FAMILY_HISTORY
|
||||
return Temporality.CURRENT
|
||||
|
||||
def _normalize_status(
|
||||
self, val: Any, temporality: Temporality, certainty: Certainty
|
||||
) -> ConditionStatus:
|
||||
"""Map status with consistency checks against temporality and certainty."""
|
||||
if certainty == Certainty.RULED_OUT:
|
||||
return ConditionStatus.RESOLVED
|
||||
if temporality == Temporality.RESOLVED:
|
||||
return ConditionStatus.RESOLVED
|
||||
if temporality == Temporality.HISTORICAL:
|
||||
return ConditionStatus.HISTORICAL
|
||||
|
||||
s = str(val or "").strip().upper()
|
||||
if "RESOLV" in s:
|
||||
return ConditionStatus.RESOLVED
|
||||
if "HISTOR" in s or "PAST" in s:
|
||||
return ConditionStatus.HISTORICAL
|
||||
if "CHRONIC" in s:
|
||||
return ConditionStatus.CHRONIC
|
||||
if "ACUTE" in s:
|
||||
return ConditionStatus.ACUTE
|
||||
if "ACTIVE" in s:
|
||||
return ConditionStatus.ACTIVE
|
||||
return ConditionStatus.ACTIVE
|
||||
|
||||
def _normalize_negation(self, val: Any) -> NegationStatus:
|
||||
"""Map negation strings to standardized NegationStatus enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "NEG" in s or "NO" in s or "DENI" in s or "ABSENT" in s:
|
||||
return NegationStatus.NEGATED
|
||||
if "UNCERTAIN" in s or "EQUIVOCAL" in s:
|
||||
return NegationStatus.UNCERTAIN
|
||||
return NegationStatus.AFFIRMATIVE
|
||||
|
||||
def _normalize_laterality(self, val: Any) -> Laterality:
|
||||
"""Map laterality strings to standardized Laterality enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "LEFT" in s:
|
||||
return Laterality.LEFT
|
||||
if "RIGHT" in s:
|
||||
return Laterality.RIGHT
|
||||
if "BILATERAL" in s or "BOTH" in s:
|
||||
return Laterality.BILATERAL
|
||||
return Laterality.UNSPECIFIED
|
||||
|
||||
def _normalize_entity_type(self, val: Any) -> ClinicalEntityType:
|
||||
"""Map entity type strings to standardized ClinicalEntityType enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "SYMPTOM" in s:
|
||||
return ClinicalEntityType.SYMPTOM
|
||||
if "SIGN" in s:
|
||||
return ClinicalEntityType.SIGN
|
||||
if "PROCEDUR" in s:
|
||||
return ClinicalEntityType.PROCEDURAL_FINDING
|
||||
return ClinicalEntityType.DIAGNOSIS
|
||||
@@ -0,0 +1,505 @@
|
||||
"""Candidate ranking agent selecting strictly from retrieved local ICD-10-CM codes."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.prompts.ranking import (
|
||||
RANKING_SYSTEM_PROMPT,
|
||||
RANKING_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.schemas.clinical import ClassifiedDiagnosis, ConditionClassification
|
||||
from medical_coding.schemas.enums import DiagnosisRole
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.utils.text import format_icd_code
|
||||
from medical_coding.validation.deterministic import (
|
||||
CandidateRankingDeterministicValidator,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class CandidateRankingAgent(BaseAgent):
|
||||
"""Evaluates retrieved local ICD candidates against evidence to select best match or abstain.
|
||||
|
||||
CORE ARCHITECTURAL INVARIANTS:
|
||||
1. The candidate ranking agent answers:
|
||||
"Which of these retrieved ICD codes is best supported by the documented clinical evidence?"
|
||||
It does NOT answer:
|
||||
"What ICD code do I know for this diagnosis?"
|
||||
2. Selected code MUST exist in the supplied candidate list.
|
||||
3. The LLM may NEVER generate or invent a new ICD code.
|
||||
4. Unsupported clinical specificity is blocked.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm: BaseLocalLLM | None = None,
|
||||
validator: CandidateRankingDeterministicValidator | None = None,
|
||||
min_confidence: float = 0.40,
|
||||
allow_rerun: bool = False,
|
||||
) -> None:
|
||||
super().__init__(llm) # type: ignore[arg-type]
|
||||
self.system_prompt = RANKING_SYSTEM_PROMPT
|
||||
self.user_template = RANKING_USER_TEMPLATE
|
||||
self.validator = validator or CandidateRankingDeterministicValidator(
|
||||
min_confidence=min_confidence
|
||||
)
|
||||
self.min_confidence = min_confidence
|
||||
self.allow_rerun = allow_rerun
|
||||
|
||||
def rank_candidates(
|
||||
self,
|
||||
condition: ClassifiedDiagnosis | ConditionClassification | Any,
|
||||
candidates: list[ICDCandidate],
|
||||
evidence_override: str | None = None,
|
||||
role_override: str | None = None,
|
||||
allow_rerun: bool | None = None,
|
||||
) -> RankedSelection:
|
||||
"""Evaluate candidate codes and select the best match or explicitly abstain.
|
||||
|
||||
Args:
|
||||
condition: Diagnosis mention, classified condition, or dict with clinical attributes.
|
||||
candidates: Top-K retrieved ICD-10-CM candidates from the local dataset.
|
||||
evidence_override: Optional explicit evidence quote override.
|
||||
role_override: Optional explicit role override.
|
||||
allow_rerun: Override for single retry on invalid code output.
|
||||
|
||||
Returns:
|
||||
RankedSelection with selected_code, selected_description, ranking_reason,
|
||||
supporting_evidence, confidence, and abstention_reason.
|
||||
"""
|
||||
# 1. Normalize and extract condition details
|
||||
diag_id, raw_term, evidence_quote, role, acuity, certainty, anatomy, laterality = (
|
||||
self._extract_condition_attributes(condition, evidence_override, role_override)
|
||||
)
|
||||
|
||||
# 2. Short-circuit: Empty candidate pool -> Immediate Abstention (No LLM call)
|
||||
if not candidates:
|
||||
logger.info(
|
||||
"Candidate pool is empty for '%s'; abstaining immediately without LLM.", raw_term
|
||||
)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason="Candidate pool was empty; no matching local ICD code.",
|
||||
supporting_evidence=[evidence_quote] if evidence_quote else [],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_CANDIDATES",
|
||||
candidate_pool=[],
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=[],
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 3. Short-circuit: Insufficient / missing evidence -> Immediate Abstention
|
||||
if not evidence_quote.strip():
|
||||
logger.info("Documentation lacks evidence quote for '%s'; abstaining.", raw_term)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason="Insufficient evidence: documentation lacks factual evidence quote.",
|
||||
supporting_evidence=[],
|
||||
confidence=0.0,
|
||||
abstention_reason="INSUFFICIENT_EVIDENCE",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=candidates,
|
||||
evidence_text="",
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 4. Short-circuit: Excluded condition -> Immediate Abstention
|
||||
if role == DiagnosisRole.EXCLUDED or role == "EXCLUDED":
|
||||
logger.info("Condition '%s' is marked as EXCLUDED; abstaining from coding.", raw_term)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason=f"Condition '{raw_term}' is excluded from billing/coding.",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=0.0,
|
||||
abstention_reason="CONDITION_EXCLUDED",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=candidates,
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 5. Format candidates into bounded prompt context
|
||||
candidates_formatted = self._format_candidates(candidates)
|
||||
prompt = self._build_prompt(
|
||||
diagnosis_term=raw_term,
|
||||
evidence_quote=evidence_quote,
|
||||
role=str(role),
|
||||
acuity=str(acuity),
|
||||
certainty=str(certainty),
|
||||
anatomical_site=str(anatomy or "Not documented"),
|
||||
laterality=str(laterality or "Unspecified"),
|
||||
candidates_formatted=candidates_formatted,
|
||||
)
|
||||
|
||||
# 6. Execute LLM inference or deterministic evaluation
|
||||
initial_selection: RankedSelection | None = None
|
||||
if self.llm is not None:
|
||||
initial_selection = self._execute_llm_ranking(
|
||||
prompt, diag_id, raw_term, evidence_quote, candidates
|
||||
)
|
||||
|
||||
# Fallback to deterministic scoring if LLM was unavailable or produced unparseable output
|
||||
if initial_selection is None:
|
||||
initial_selection = self._evaluate_candidates_deterministically(
|
||||
diag_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
evidence_quote=evidence_quote,
|
||||
acuity=acuity,
|
||||
candidates=candidates,
|
||||
)
|
||||
|
||||
# 7. Check Hard Constraint: Is proposed code in candidates list?
|
||||
rerun_flag = self.allow_rerun if allow_rerun is None else allow_rerun
|
||||
if (
|
||||
initial_selection.selected_code is not None
|
||||
and not any(
|
||||
format_icd_code(initial_selection.selected_code) == format_icd_code(c.code)
|
||||
for c in candidates
|
||||
)
|
||||
and rerun_flag
|
||||
and self.llm is not None
|
||||
):
|
||||
# One retry with explicit error feedback
|
||||
logger.warning(
|
||||
"LLM proposed invalid code '%s' not in candidates. Triggering single rerun with bounded instruction.",
|
||||
initial_selection.selected_code,
|
||||
)
|
||||
rerun_prompt = (
|
||||
f"{prompt}\n\n"
|
||||
f"CORRECTION ERROR: Your previous selection '{initial_selection.selected_code}' is NOT in the candidate list.\n"
|
||||
f"You are strictly forbidden from inventing codes. Choose ONLY from: {[c.code for c in candidates]} or output null.\n"
|
||||
f"Output valid JSON only:"
|
||||
)
|
||||
initial_selection = (
|
||||
self._execute_llm_ranking(
|
||||
rerun_prompt, diag_id, raw_term, evidence_quote, candidates
|
||||
)
|
||||
or initial_selection
|
||||
)
|
||||
|
||||
# 8. Deterministic Validation immediately after LLM
|
||||
validated_selection = self.validator.validate_ranking_selection(
|
||||
selection=initial_selection,
|
||||
candidates=candidates,
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
return validated_selection
|
||||
|
||||
def run(self, **kwargs: Any) -> RankedSelection:
|
||||
"""Standard pipeline invocation interface."""
|
||||
condition = kwargs.get("condition")
|
||||
candidates = kwargs.get("candidates", [])
|
||||
evidence_override = kwargs.get("evidence")
|
||||
role_override = kwargs.get("role")
|
||||
return self.rank_candidates(
|
||||
condition=condition,
|
||||
candidates=candidates,
|
||||
evidence_override=evidence_override,
|
||||
role_override=role_override,
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Internal Helpers
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _extract_condition_attributes(
|
||||
self,
|
||||
condition: Any,
|
||||
evidence_override: str | None,
|
||||
role_override: str | None,
|
||||
) -> tuple[str, str, str, str, str, str, str | None, str | None]:
|
||||
"""Extract and normalize clinical attributes across various diagnosis representations."""
|
||||
diag_id = "diag-unknown"
|
||||
raw_term = "Unknown Diagnosis"
|
||||
evidence_quote = ""
|
||||
role = "SECONDARY"
|
||||
acuity = "UNSPECIFIED"
|
||||
certainty = "CONFIRMED"
|
||||
anatomy = None
|
||||
laterality = "UNSPECIFIED"
|
||||
|
||||
if hasattr(condition, "diagnosis_id"):
|
||||
diag_id = str(condition.diagnosis_id)
|
||||
if hasattr(condition, "raw_term"):
|
||||
raw_term = str(condition.raw_term)
|
||||
elif hasattr(condition, "diagnosis"):
|
||||
raw_term = str(condition.diagnosis)
|
||||
|
||||
# Evidence resolution
|
||||
if evidence_override:
|
||||
evidence_quote = evidence_override
|
||||
elif hasattr(condition, "evidence_quote") and condition.evidence_quote:
|
||||
evidence_quote = condition.evidence_quote
|
||||
elif hasattr(condition, "evidence_text") and condition.evidence_text:
|
||||
evidence_quote = condition.evidence_text
|
||||
elif hasattr(condition, "context") and hasattr(condition.context, "evidence"):
|
||||
evidence_quote = getattr(condition.context.evidence, "quote", "")
|
||||
|
||||
# Role resolution
|
||||
if role_override:
|
||||
role = role_override
|
||||
elif hasattr(condition, "role"):
|
||||
role = str(condition.role.value if hasattr(condition.role, "value") else condition.role)
|
||||
|
||||
# Context details
|
||||
if hasattr(condition, "context"):
|
||||
ctx = condition.context
|
||||
if hasattr(ctx, "acuity"):
|
||||
acuity = str(ctx.acuity.value if hasattr(ctx.acuity, "value") else ctx.acuity)
|
||||
if hasattr(ctx, "certainty"):
|
||||
certainty = str(
|
||||
ctx.certainty.value if hasattr(ctx.certainty, "value") else ctx.certainty
|
||||
)
|
||||
|
||||
if hasattr(condition, "anatomical_site") and condition.anatomical_site:
|
||||
anatomy = str(condition.anatomical_site)
|
||||
if hasattr(condition, "laterality"):
|
||||
laterality = str(
|
||||
condition.laterality.value
|
||||
if hasattr(condition.laterality, "value")
|
||||
else condition.laterality
|
||||
)
|
||||
|
||||
return diag_id, raw_term, evidence_quote, role, acuity, certainty, anatomy, laterality
|
||||
|
||||
def _format_candidates(self, candidates: list[ICDCandidate]) -> str:
|
||||
"""Format candidate list with indices and clinical details for the prompt."""
|
||||
lines: list[str] = []
|
||||
for i, c in enumerate(candidates, start=1):
|
||||
billable_str = "Billable" if c.is_valid_billable else "Non-Billable Header"
|
||||
lines.append(
|
||||
f"Candidate [{i}]: Code: {c.code} | Description: {c.description} | "
|
||||
f"Retrieval Score: {c.retrieval_score:.4f} | Status: {billable_str}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
def _build_prompt(
|
||||
self,
|
||||
diagnosis_term: str,
|
||||
evidence_quote: str,
|
||||
role: str,
|
||||
acuity: str,
|
||||
certainty: str,
|
||||
anatomical_site: str,
|
||||
laterality: str,
|
||||
candidates_formatted: str,
|
||||
) -> str:
|
||||
"""Construct prompt combining system instructions and formatted clinical parameters."""
|
||||
user_body = self.user_template.format(
|
||||
diagnosis_term=diagnosis_term,
|
||||
evidence_quote=evidence_quote,
|
||||
role=role,
|
||||
acuity=acuity,
|
||||
certainty=certainty,
|
||||
anatomical_site=anatomical_site,
|
||||
laterality=laterality,
|
||||
candidates_formatted=candidates_formatted,
|
||||
)
|
||||
return f"{self.system_prompt}\n\n{user_body}"
|
||||
|
||||
def _execute_llm_ranking(
|
||||
self,
|
||||
prompt: str,
|
||||
diag_id: str,
|
||||
raw_term: str,
|
||||
evidence_quote: str,
|
||||
candidates: list[ICDCandidate],
|
||||
) -> RankedSelection | None:
|
||||
"""Execute LLM call and parse structured response."""
|
||||
try:
|
||||
assert self.llm is not None
|
||||
response_text = self.llm.generate(prompt=prompt, max_tokens=512, temperature=0.0)
|
||||
if not response_text or not response_text.strip():
|
||||
return None
|
||||
|
||||
json_match = re.search(r"(\{.*\})", response_text, re.DOTALL)
|
||||
if not json_match:
|
||||
return None
|
||||
|
||||
parsed = json.loads(json_match.group(1))
|
||||
|
||||
raw_code = parsed.get("selected_code")
|
||||
code_str = (
|
||||
str(raw_code).strip() if raw_code and str(raw_code).lower() != "null" else None
|
||||
)
|
||||
desc_str = parsed.get("selected_description")
|
||||
reason = parsed.get("ranking_reason") or parsed.get("justification", "")
|
||||
confidence = float(parsed.get("confidence", parsed.get("confidence_score", 0.85)))
|
||||
decision = parsed.get("decision", "ACCEPTED" if code_str else "ABSTAINED")
|
||||
abstention_reason = parsed.get("abstention_reason")
|
||||
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=code_str,
|
||||
selected_description=desc_str,
|
||||
ranking_reason=reason,
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=confidence,
|
||||
abstention_reason=abstention_reason,
|
||||
candidate_pool=candidates,
|
||||
decision=decision,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Error executing LLM ranking: %s. Using deterministic evaluation.", e)
|
||||
return None
|
||||
|
||||
def _evaluate_candidates_deterministically(
|
||||
self,
|
||||
diag_id: str,
|
||||
raw_term: str,
|
||||
evidence_quote: str,
|
||||
acuity: str,
|
||||
candidates: list[ICDCandidate],
|
||||
) -> RankedSelection:
|
||||
"""Deterministic evidence-based candidate scoring when offline or in test environments."""
|
||||
evidence_clean = (evidence_quote or "").lower()
|
||||
term_clean = (raw_term or "").lower()
|
||||
full_context = f"{term_clean} {evidence_clean}"
|
||||
|
||||
scored_candidates: list[tuple[ICDCandidate, float, str]] = []
|
||||
|
||||
for cand in candidates:
|
||||
score = cand.retrieval_score
|
||||
desc_lower = cand.description.lower()
|
||||
rationale_parts: list[str] = []
|
||||
|
||||
# 1. Non-billable penalty
|
||||
if not cand.is_valid_billable:
|
||||
score *= 0.5
|
||||
rationale_parts.append("non-billable category header")
|
||||
|
||||
# 2. Terminology and specific descriptor matches
|
||||
cand_tokens = [t for t in re.findall(r"[a-z0-9]+", desc_lower) if len(t) > 2]
|
||||
overlap = [t for t in cand_tokens if t in full_context]
|
||||
if overlap:
|
||||
score += 0.15 * (len(overlap) / len(cand_tokens))
|
||||
|
||||
# 3. Acuity alignment
|
||||
is_acute_doc = any(
|
||||
w in full_context
|
||||
for w in ["acute", "exacerbation", "decompensated", "decompensation"]
|
||||
)
|
||||
is_chronic_doc = any(
|
||||
w in full_context for w in ["chronic", "compensated", "longstanding"]
|
||||
)
|
||||
|
||||
is_acute_cand = "acute" in desc_lower and "chronic" not in desc_lower
|
||||
is_chronic_cand = "chronic" in desc_lower and "acute" not in desc_lower
|
||||
is_acute_on_chronic_cand = "acute on chronic" in desc_lower or (
|
||||
"acute" in desc_lower and "chronic" in desc_lower
|
||||
)
|
||||
|
||||
if is_acute_on_chronic_cand:
|
||||
if is_acute_doc and is_chronic_doc:
|
||||
score += 0.25
|
||||
rationale_parts.append("acute on chronic documentation match")
|
||||
elif not is_acute_doc or not is_chronic_doc:
|
||||
score -= 0.30
|
||||
elif is_acute_cand:
|
||||
if is_acute_doc and not is_chronic_doc:
|
||||
score += 0.20
|
||||
rationale_parts.append("acute acuity match")
|
||||
elif is_chronic_doc and not is_acute_doc:
|
||||
score -= 0.25
|
||||
elif is_chronic_cand:
|
||||
if is_chronic_doc and not is_acute_doc:
|
||||
score += 0.20
|
||||
rationale_parts.append("chronic acuity match")
|
||||
elif is_acute_doc and not is_chronic_doc:
|
||||
score -= 0.25
|
||||
|
||||
# 4. Specificity penalty for unsupported subtypes
|
||||
# Heart failure: systolic / diastolic
|
||||
if "systolic" in desc_lower and not any(
|
||||
w in full_context for w in ["systolic", "hfref", "reduced ejection"]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported systolic specificity")
|
||||
if "diastolic" in desc_lower and not any(
|
||||
w in full_context for w in ["diastolic", "hfpef", "preserved ejection"]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported diastolic specificity")
|
||||
|
||||
# Diabetes complications
|
||||
if any(
|
||||
comp in desc_lower
|
||||
for comp in ["nephropathy", "retinopathy", "neuropathy", "hyperglycemia"]
|
||||
):
|
||||
if not any(
|
||||
comp in full_context
|
||||
for comp in [
|
||||
"nephropathy",
|
||||
"kidney",
|
||||
"retinopathy",
|
||||
"neuropathy",
|
||||
"hyperglycemia",
|
||||
"uncontrolled",
|
||||
]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported complication specificity")
|
||||
|
||||
clamped_score = max(0.0, min(1.0, round(score, 4)))
|
||||
scored_candidates.append(
|
||||
(cand, clamped_score, ", ".join(rationale_parts) or "evidence overlap")
|
||||
)
|
||||
|
||||
# Sort descending by score
|
||||
scored_candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
top_cand, top_score, top_rationale = scored_candidates[0]
|
||||
|
||||
if top_score < self.min_confidence:
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason=f"No candidate met the minimum confidence threshold ({top_score:.2f} < {self.min_confidence:.2f}).",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=top_score,
|
||||
abstention_reason="CONFIDENCE_BELOW_THRESHOLD",
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_LOW_CONFIDENCE",
|
||||
)
|
||||
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=top_cand.code,
|
||||
selected_description=top_cand.description,
|
||||
selected_candidate=top_cand,
|
||||
ranking_reason=f"Candidate '{top_cand.code}' ({top_cand.description}) best supported by documentation ({top_rationale}).",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=top_score,
|
||||
abstention_reason=None,
|
||||
candidate_pool=candidates,
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
Reference in New Issue
Block a user