Fix a broken medical message routing classifier
Machine LearningModel answerLast updated
Debug a telehealth triage service that returns wrong categories with negative confidence scores, then redesign the classification and escalation logic.
You're working on a telehealth platform where incoming patient messages must be routed to the appropriate care team. The existing service classifies messages into clinical categories (like "upper respiratory," "dermatology," etc.) and assigns an urgency level and confidence score.
The service exposes three endpoints:
triage(msg: str) -> dict # returns: message, category, urgency, confidence_level
get_categories() -> list[str]
health_check()
The engineering team reports that classification accuracy is poor. Initial testing reveals that vague patient messages return obviously incorrect categories paired with negative confidence_level values, and these results are sent directly to callers without any filtering or review.
You have one hour to investigate, fix the core issues, and document your findings.
An external LLM API is available if needed. You may use an AI coding assistant during the exercise.
Your Task
Part 1: Investigation (15–20 minutes)
Describe your debugging approach. What would you check in the code and response structure? Which test inputs would you use? What does the "negative confidence with wrong answer" symptom suggest about the underlying bugs?
Part 2: Implementation (25–30 minutes)
Refactor the triage function to stop returning confident-looking incorrect results. Design a decision path that determines when to:
- Return a classification directly
- Call the LLM API for ambiguous cases
- Escalate to manual review
Explain how you'll prevent the LLM from introducing new errors, and how you'll handle urgency differently than category assignment.
Part 3: Documentation (10–15 minutes)
Write a brief report covering:
- Bugs found, with evidence
- How you prioritized fixes
- Trade-offs made (latency, cost, review load, accuracy)
- What you'd build next with more time
Clarifying Questions to Consider
- Is there a labeled test set, or do you need to create probe cases?
- What is the intended range and semantics of
confidence_level? - Are there privacy or compliance constraints on sending patient messages to external APIs?
- Which error is more costly: wrong department routing, or missed urgent cases?
- Does a manual review queue already exist?
- Must the response format remain backward compatible?
Hints
Hint 1
Start by examining edge cases: empty strings, very short messages, and out-of-domain content to understand how confidence is calculated
Hint 2
A negative confidence score suggests a logic error or missing validation, not just model uncertainty
Hint 3
For a safety-critical system, the cost of a false negative on urgency (missing something serious) is much higher than a false positive (extra caution)
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Investigation Strategy
Code Review Priorities
First, examine the triage function implementation:
- How is
confidence_levelcomputed? Negative values indicate a calculation bug or unhandled case - Are there any validation steps on the input message or model output?
- What happens when the underlying model returns low-confidence or malformed results?
- Check if
categoryvalues are validated againstget_categories()
Systematic Probing
Test across multiple failure modes within 10 minutes:
# Edge cases that expose validation gaps
test_cases = [
"", # empty
"hi", # too short to classify
"asdfjkl", # nonsense
"I need to schedule an appointment", # administrative, not clinical
"My chest hurts and I can't breathe", # urgent
"I have a slight headache", # vague but probably non-urgent
"Can you refill my prescription?", # pharmacy/admin
]
Probe each case and record the full response dictionary. Check:
- Does
confidence_levelever go negative? If so, when? - Are returned categories always in the valid set from
get_categories()? - Does
urgencycorrelate sensibly with message content? - Are there cases where the model returns
Noneor unexpected keys?
Likely Bug Classes
The "vague message → wrong category + negative confidence" symptom suggests:
- Confidence calculation bug: Likely taking
logof a probability near zero without bounds checking, or subtracting values in the wrong order - No abstention path: The system always picks some category even when it shouldn't
- Missing input validation: No check for empty, too-short, or out-of-domain messages
- No output validation: Results aren't sanity-checked before returning
Implementation: Fixed Triage Logic
Core Principles
- Safety first: For urgency, err on the side of caution; for routing, prefer human review over a wrong guess
- Confidence must be meaningful: Use it to decide whether to trust the classification
- Defense in depth: Validate inputs, model outputs, and LLM responses
Decision Flow
def triage(msg: str) -> dict:
# Input validation
if not msg or len(msg.strip()) < 5:
return {
"message": msg,
"category": "NEEDS_REVIEW",
"urgency": "medium", # safe default
"confidence_level": 0.0,
"reason": "insufficient_input"
}
# Get base classification
result = base_classifier(msg)
# Fix confidence calculation (was likely: log(prob) or prob - threshold)
# Should be: the raw probability or a properly bounded score
raw_confidence = result.get("confidence", 0.0)
confidence = max(0.0, min(1.0, raw_confidence)) # clamp to [0, 1]
category = result.get("category", "UNKNOWN")
urgency = result.get("urgency", "medium")
# Validate category
valid_categories = set(get_categories())
if category not in valid_categories:
category = "NEEDS_REVIEW"
confidence = 0.0
# Decision paths
HIGH_CONF_THRESHOLD = 0.75
LOW_CONF_THRESHOLD = 0.40
# Path 1: High confidence → return directly
if confidence >= HIGH_CONF_THRESHOLD:
return build_response(msg, category, urgency, confidence)
# Path 2: Very low confidence → manual review
if confidence < LOW_CONF_THRESHOLD:
return build_response(
msg,
"NEEDS_REVIEW",
escalate_urgency_if_keywords(msg, urgency),
confidence
)
# Path 3: Medium confidence → try LLM
try:
llm_result = call_llm_triage(msg, category, urgency)
validated = validate_llm_output(llm_result, valid_categories)
# Trust LLM only if it's more confident
if validated["confidence"] > confidence:
return build_response(
msg,
validated["category"],
validated["urgency"],
validated["confidence"]
)
except Exception as e:
log_error(f"LLM call failed: {e}")
# Fall through to base result
# Fallback: return base result but mark for review if urgency is high
if urgency == "high":
return build_response(msg, "NEEDS_REVIEW", urgency, confidence)
return build_response(msg, category, urgency, confidence)
def escalate_urgency_if_keywords(msg: str, current_urgency: str) -> str:
"""Conservative urgency handling: keyword scan for safety."""
urgent_keywords = [
"chest pain", "can't breathe", "suicide", "bleeding heavily",
"severe", "emergency", "unresponsive"
]
msg_lower = msg.lower()
if any(kw in msg_lower for kw in urgent_keywords):
return "high"
return current_urgency
def validate_llm_output(llm_result: dict, valid_categories: set) -> dict:
"""Ensure LLM response is well-formed and safe."""
category = llm_result.get("category", "NEEDS_REVIEW")
if category not in valid_categories:
category = "NEEDS_REVIEW"
urgency = llm_result.get("urgency", "medium")
if urgency not in ["low", "medium", "high"]:
urgency = "medium"
confidence = llm_result.get("confidence", 0.5)
confidence = max(0.0, min(1.0, confidence))
return {
"category": category,
"urgency": urgency,
"confidence": confidence
}
Urgency Handling
Urgency errors are asymmetric: missing an urgent case is far more costly than over-triaging. Therefore:
- Use keyword scanning as a safety net
- Default to "medium" when uncertain, not "low"
- Route high-urgency + low-confidence cases to review, not to a guessed department
Write-Up: Bugs, Priorities, and Trade-offs
Bugs Found
-
Critical: Negative confidence scores — Likely caused by
log(p)orp - thresholdwithout bounds checking. Evidence: vague inputs return values like-0.3. -
Critical: No abstention logic — The classifier always returns a category, even for empty or nonsense input. Evidence: "" returns a category with negative confidence.
-
High: Missing output validation — Categories are not checked against the valid set; urgency is not checked for valid values.
-
High: No fallback for low confidence — Results are returned to callers regardless of confidence, with no escalation path.
-
Medium: No urgency safety net — The model alone determines urgency; no keyword-based override for clearly dangerous terms.
Prioritization
- Fix confidence calculation first (prevents negative values from propagating)
- Add manual review path (stops wrong answers from reaching patients)
- Add urgency keywords (patient safety)
- Integrate LLM fallback (improves accuracy in the medium-confidence range)
Trade-offs
| Decision | Benefit | Cost |
|---|---|---|
| LLM for medium confidence | +10-15% accuracy | +200ms latency, +$0.001/call |
| Manual review threshold at 0.4 | Fewer routing errors | 20-30% of messages need review |
| Urgency keyword override | Catches model misses on serious cases | ~2% false positives routed as urgent |
| Conservative urgency default | Safer for patients | Slightly higher review load |
Next Steps with More Time
- Build a labeled evaluation set (200+ real anonymized messages) and compute precision/recall per category and urgency level
- A/B test thresholds for LLM calls and manual review to optimize the accuracy/cost trade-off
- Monitor in production: track review rate, override frequency, and time-to-clinician by urgency
- Collect feedback: let reviewers flag especially bad misclassifications to retrain or tune the base model
- Add structured output parsing for the LLM to reduce hallucination risk (e.g., JSON mode with schema validation)
Measurement Plan
- Accuracy: weekly evaluation on held-out labeled set
- Safety: daily report of high-urgency cases and their resolution times
- Efficiency: review rate, LLM call rate, P95 latency
- Cost: LLM API spend, review hours per 1,000 messages