Spaces:
Sleeping
fix: only explicit refusals decline the Spiritual Health referral
Browse filesAny consent answer that was not a clear yes or a question used to count as
a refusal, so a patient answering with more distress ("praying doesn't help
anymore") got "I understand and respect your decision" and lost the referral.
Keyword matching was also substring-based ("I know" hit "no", "мене" hit "не").
- Classify consent answers as accept / decline / unclear with word-boundary
patterns; negated accept words ("not ok") are not consent
- Short explicit refusals (<= 3 words) decline without an LLM call; longer
answers with refusal words are checked for distress first
- Unclear answer with new distress keeps the consent request open; otherwise
re-ask once, then close softly without a referral
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Files changed (2)
13 unmodified lines141516171819179 unmodified lines199200201202203204205213 unmodified lines4194204214224234244254264274284294304318 unmodified lines44044144244344444544644744844945045145245345445545645745845946046135 unmodified lines49749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155213 unmodified linesimport osimport sysimport loggingfrom datetime import datetimefrom dataclasses import asdictfrom typing import List, Tuple, Optional179 unmodified lines# Route based on current spiritual stateif self.spiritual_state.is_awaiting_consent():# Currently awaiting consent response - handle itresponse = self._handle_consent_response(message)elif self.spiritual_state.is_in_triage():# Currently in YELLOW state - continue triageresponse = self._handle_triage_response(message, conversation_context)213 unmodified linesreturn consent_responsedef _handle_consent_response(self, message: str) -> str:"""Handle patient's response to consent request.If patient asks about the service → explain it and keep awaiting consentIf patient agrees → generate referralIf patient declines → return to medical dialog without referralRequirement: Or_review.md section 4.A.3"""8 unmodified lineslogger.info("Patient asked about the spiritual care team - explaining service")return self._explain_spiritual_care_service(patient_language)# Check if patient consentsconsent_given = self._check_consent(message)if consent_given:logger.info("Patient consented to spiritual care referral")return self._process_consent_accepted(patient_language)else:logger.info("Patient declined spiritual care referral")return self._process_consent_declined(patient_language)def _is_consent_question(self, message: str) -> bool:"""Check whether the patient is asking about the spiritual care team ratherthan accepting or refusing the referral.This must be checked before _check_consent: phrases like "I don't know,who are they" contain negative keywords ("don't", "not") and wouldotherwise be scored as a refusal."""35 unmodified linesWould you be open to having someone from the team reach out to you?"""def _check_consent(self, message: str) -> bool:"""Check if patient's response indicates consent.Returns True if patient agrees, False if declines or unclear."""message_lower = message.lower()# Positive consent indicators (English)positive_en = ["yes", "yeah", "yep", "sure", "okay", "ok", "please", "i would","that would be", "i'd like", "sounds good", "go ahead", "i agree","i consent", "you can", "that's fine", "i'm open", "i accept"]# Positive consent indicators (Ukrainian)positive_uk = ["так", "добре", "гаразд", "будь ласка", "я згоден", "я згодна","можна", "звичайно", "я хочу", "я б х��тів", "я б хотіла","це було б", "я відкритий", "я відкрита", "погоджуюсь"]# Negative consent indicators (English)negative_en = ["no", "nope", "not", "don't", "do not", "i don't want","no thanks", "no thank you", "i'm not", "i am not","i decline", "i refuse", "not interested", "not now","maybe later", "not right now", "i'd rather not"]# Negative consent indicators (Ukrainian)negative_uk = ["ні", "не", "не хочу", "не треба", "не потрібно","дякую, ні", "я не хочу", "я відмовляюсь", "не зараз","можливо пізніше", "краще ні", "не цікавить"]# Check for negative first (more conservative)for neg in negative_en + negative_uk:if neg in message_lower:return False# Check for positivefor pos in positive_en + positive_uk:if pos in message_lower:return True# If unclear, treat as decline (respect patient autonomy)return Falsedef _process_consent_accepted(self, language: str) -> str:"""Process accepted consent - generate and log referral."""# Get pending referral data13 unmodified lines14151617181920179 unmodified lines200201202203204205206213 unmodified lines4204214224234244254264274284294304314324334344358 unmodified lines44444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952035 unmodified lines55655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160213 unmodified linesimport osimport sysimport loggingimport refrom datetime import datetimefrom dataclasses import asdictfrom typing import List, Tuple, Optional179 unmodified lines# Route based on current spiritual stateif self.spiritual_state.is_awaiting_consent():# Currently awaiting consent response - handle itresponse = self._handle_consent_response(message, conversation_context)elif self.spiritual_state.is_in_triage():# Currently in YELLOW state - continue triageresponse = self._handle_triage_response(message, conversation_context)213 unmodified linesreturn consent_responsedef _handle_consent_response(self, message: str, conversation_context: Optional[List[str]] = None) -> str:"""Handle patient's response to consent request.If patient asks about the service → explain it and keep awaiting consentIf patient agrees → generate referralIf patient explicitly declines → return to medical dialog without referralIf the answer is unclear → never treat it as a refusal (Or_7 final test):new distress → acknowledge and keep the consent request openotherwise → gently re-ask once, then close softly without referralRequirement: Or_review.md section 4.A.3"""8 unmodified lineslogger.info("Patient asked about the spiritual care team - explaining service")return self._explain_spiritual_care_service(patient_language)decision = self._classify_consent_response(message)if decision == "accept":logger.info("Patient consented to spiritual care referral")return self._process_consent_accepted(patient_language)if decision == "decline":# Only a short, explicit refusal skips the distress check: longer# answers like "no one cares anymore" or "не хочу жити" contain# refusal words but are not refusals.if len(message.split()) <= 3 or not self._shows_new_distress(message, conversation_context):logger.info("Patient declined spiritual care referral")return self._process_consent_declined(patient_language)return self._keep_consent_open(patient_language)return self._handle_unclear_consent(message, patient_language, conversation_context)def _shows_new_distress(self, message: str, conversation_context: Optional[List[str]] = None) -> bool:"""Whether a consent-stage answer itself expresses distress (YELLOW or RED)."""assessment = self.spiritual_monitor.classify(message, conversation_context)return assessment.state in (SpiritualState.YELLOW, SpiritualState.RED)def _keep_consent_open(self, language: str) -> str:"""Acknowledge new distress and repeat the consent question (state stays AWAITING_CONSENT)."""logger.info("Consent answer with new distress - keeping consent request open")if language == "Ukrainian":return """Дякую, що поділились цим — схоже, вам зараз нелегко. Розмова з кимось із нашої команди духовного здоров'я може допомогти.Чи були б ви відкриті до того, щоб хтось із команди зв'язався з вами?"""return """Thank you for telling me that — it sounds like a lot to carry. Talking with someone from our Spiritual Health team might help.Would you be open to having someone from the team reach out to you?"""def _handle_unclear_consent(self,message: str,language: str,conversation_context: Optional[List[str]] = None) -> str:"""Handle an answer that is neither consent, refusal, nor a question.A patient who answers the consent question with more distress("praying doesn't help anymore") must not be read as declining."""if self._shows_new_distress(message, conversation_context):return self._keep_consent_open(language)pending = self.spiritual_state.pending_referral or {}if not pending.get("reasked"):logger.info("Unclear consent answer - re-asking once")pending["reasked"] = Trueself.spiritual_state.pending_referral = pendingif language == "Ukrainian":return """Жодного тиску — я лише хочу переконатися, що правильно вас зрозумів. Чи хотіли б ви, щоб хтось із нашої команди духовного здоров'я зв'язався з вами? Достатньо відповісти «так» чи «ні»."""return """No pressure at all — I just want to make sure I understood you. Would you like someone from our Spiritual Health team to reach out to you? A simple yes or no is fine."""logger.info("Still no clear consent after re-asking - closing softly without referral")self._process_consent_declined(language)if language == "Ukrainian":return """Нічого страшного — вирішувати зараз не обов'язково. Якщо згодом захочете, щоб хтось із нашої команди духовного здоров'я зв'язався з вами, просто скажіть мені.Чи є щось інше, з чим я можу вам допомогти сьогодні?"""return """That's okay — you don't need to decide now. If you'd like someone from our Spiritual Health team to reach out later, just let me know.Is there anything else I can help you with today?"""def _is_consent_question(self, message: str) -> bool:"""Check whether the patient is asking about the spiritual care team ratherthan accepting or refusing the referral.This must be checked before _classify_consent_response: phrases like "I don't know,who are they" contain negative keywords ("don't", "not") and wouldotherwise be scored as a refusal."""35 unmodified linesWould you be open to having someone from the team reach out to you?"""# Only explicit refusals count as a decline; anything unclear is re-asked# rather than silently treated as "no" (Or_7 final test)._DECLINE_PATTERNS = [r"^\W*(?:no|nope|nah)\b", r"\bno,?\s+thanks?\b", r"\bno thank you\b", r"\bnot now\b", r"\bnot right now\b",r"\bmaybe later\b", r"\bnot interested\b",r"\bi (?:don'?t|do not) (?:want|need) (?:that|it|this|them|anyone|someone|any help|to be contacted)\b", r"\bi decline\b",r"\bi refuse\b", r"\bi'?d rather not\b", r"\bnot for me\b",r"\bi'?m (?:fine|okay|ok|good)\b(?! with)", r"\bi am (?:fine|okay|ok|good)\b(?! with)",r"^\W*ні\b", r"\bне хочу\b", r"\bне треба\b", r"\bне потрібно\b", r"\bне зараз\b",r"\bможливо пізніше\b", r"\bкраще ні\b", r"\bне цікавить\b", r"\bвідмовляюсь\b",r"\bу мене все (?:добре|гаразд)\b", r"\bзі мною все (?:добре|гаразд)\b",]_ACCEPT_PATTERNS = [r"\byes\b", r"\byeah\b", r"\byep\b", r"\bsure\b", r"\bokay\b", r"\bok\b",r"\bplease\b", r"\bi would\b", r"\bthat would be\b", r"\bi'?d like\b",r"\bsounds good\b", r"\bgo ahead\b", r"\bi agree\b", r"\bi consent\b",r"\bthat'?s fine\b", r"\bfine with\b", r"\bi'?m open\b", r"\bi accept\b",r"\bтак\b", r"\bдобре\b", r"\bгаразд\b", r"\bбудь ласка\b", r"\bзгод(?:ен|на)\b",r"\bможна\b", r"\bзвичайно\b", r"\bя хочу\b", r"\bя б хоті(?:в|ла)\b",r"\bпогоджуюсь\b", r"\bвідкрит(?:ий|а)\b",]_NEGATED_ACCEPT = r"\b(?:not|don'?t|doesn'?t|не)\s+(?:so\s+)?(?:sure|okay|ok|fine|good|добре|гаразд)\b"def _classify_consent_response(self, message: str) -> str:"""Classify the patient's answer to the consent question.Returns "accept", "decline" or "unclear". Explicit refusals win overaccept words ("no, I'm okay"); negated accept words ("not okay") arenot consent."""message_lower = message.lower().replace("’", "'")if any(re.search(p, message_lower) for p in self._DECLINE_PATTERNS):return "decline"if re.search(self._NEGATED_ACCEPT, message_lower):return "unclear"if any(re.search(p, message_lower) for p in self._ACCEPT_PATTERNS):return "accept"return "unclear"def _process_consent_accepted(self, language: str) -> str:"""Process accepted consent - generate and log referral."""# Get pending referral data
77 unmodified lines78798077 unmodified linesassert "confidential" not in joinedassert "share your information" not in joinedassert "Spiritual Health team" in " ".join(templates)77 unmodified lines7879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116277 unmodified linesassert "confidential" not in joinedassert "share your information" not in joinedassert "Spiritual Health team" in " ".join(templates)# --- Consent answers: only explicit refusals decline (Or_7 final test) -------import pytestfrom src.core.spiritual_state import SpiritualAssessment, SpiritualStatedef _awaiting_consent_app(monkeypatch, classified_as=SpiritualState.GREEN):app = SimplifiedMedicalApp()calls = []def fake_classify(message, conversation_history=None):calls.append(message)return SpiritualAssessment(state=classified_as, indicators=[], confidence=0.9, reasoning="stub")monkeypatch.setattr(app.spiritual_monitor, "classify", fake_classify)red = SpiritualAssessment(state=SpiritualState.RED, indicators=["x"], confidence=0.9, reasoning="stub")app.spiritual_state.last_assessment = redapp.spiritual_state.pending_referral = {"assessment": red, "language": "English", "original_message": ""}app.spiritual_state.transition_to(SpiritualState.AWAITING_CONSENT, "test")return app, calls@pytest.mark.parametrize("message, expected", [("yes", "accept"), ("ok", "accept"), ("sure", "accept"), ("I'm fine with that", "accept"),("так", "accept"), ("добре", "accept"),("no", "decline"), ("No thanks", "decline"), ("not now", "decline"), ("I'm fine", "decline"),("no, I'm okay", "decline"), ("ні", "decline"), ("не зараз", "decline"),("a little bit both", "unclear"), ("praying doesn't help anymore", "unclear"),("I'm not ok", "unclear"), ("feeling worried", "unclear"),("I know", "unclear"), # used to hit the "no" substring and count as a refusal("мене це турбує", "unclear"), # used to hit the "не" substring])def test_classify_consent_response(message, expected):assert SimplifiedMedicalApp._classify_consent_response(SimplifiedMedicalApp, message) == expecteddef test_new_distress_keeps_consent_open(monkeypatch):app, _ = _awaiting_consent_app(monkeypatch, classified_as=SpiritualState.RED)response = app._handle_consent_response("praying doesn't help anymore")assert app.spiritual_state.is_awaiting_consent()assert app.spiritual_state.pending_referral is not Noneassert "respect your decision" not in responseassert "Would you be open to having someone from the team reach out to you?" in responsedef test_long_answer_with_refusal_words_but_distress_is_not_a_decline(monkeypatch):app, calls = _awaiting_consent_app(monkeypatch, classified_as=SpiritualState.RED)app._handle_consent_response("No one cares about me anymore")assert calls == ["No one cares about me anymore"]assert app.spiritual_state.is_awaiting_consent()def test_short_explicit_refusal_declines_without_llm(monkeypatch):app, calls = _awaiting_consent_app(monkeypatch)response = app._handle_consent_response("no thanks")assert calls == []assert app.spiritual_state.spiritual_state == SpiritualState.GREENassert app.spiritual_state.pending_referral is Noneassert "respect your decision" in responsedef test_unclear_answer_is_reasked_once_then_closed_softly(monkeypatch):app, _ = _awaiting_consent_app(monkeypatch, classified_as=SpiritualState.GREEN)first = app._handle_consent_response("a little bit both")assert app.spiritual_state.is_awaiting_consent()assert "A simple yes or no is fine." in firstsecond = app._handle_consent_response("hmm whatever")assert app.spiritual_state.spiritual_state == SpiritualState.GREENassert app.spiritual_state.pending_referral is Noneassert "you don't need to decide now" in secondassert "respect your decision" not in second