From cc2ed7f78aab5f8b47eccb7179252d24462cabaa Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Mon, 16 Nov 2026 11:37:50 +0800 Subject: [PATCH 1/2] Fix #5: stop locking a session in emergency mode after one high-risk turn - Re-evaluate risk from the current message every turn instead of carrying a sticky high/watch level forever; the earlier emergency turn is preserved in risk_history and surfaced once as a brief reminder in the first normal answer afterwards. - Emergency advice now names 120 (China emergency number) in both workflow.py and safety.py, and emergency answers also carry the standard disclaimer. - Update the regression test that enshrined the sticky behaviour and add backend/tests/test_emergency_unlock.py (6 tests). Closes zhengdaodeguL/MedGuide#5. --- backend/app/safety.py | 2 +- backend/app/workflow.py | 38 +++++-- backend/tests/test_emergency_unlock.py | 105 ++++++++++++++++++ .../test_workflow_and_safety_regressions.py | 16 ++- 4 files changed, 145 insertions(+), 16 deletions(-) create mode 100644 backend/tests/test_emergency_unlock.py diff --git a/backend/app/safety.py b/backend/app/safety.py index fa9a4e7..3966c19 100644 --- a/backend/app/safety.py +++ b/backend/app/safety.py @@ -244,7 +244,7 @@ def screen(self, text: str, profile: PatientProfile | None = None) -> RiskAssess break if flags: - advice = "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。" + advice = "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。" return RiskAssessment("high", tuple(dict.fromkeys(flags)), advice) watch_flags = [ diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 5dbcc68..2a63b74 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -585,19 +585,23 @@ def intent(self, state: WorkflowState) -> WorkflowState: return state def risk(self, state: WorkflowState) -> WorkflowState: + # Risk is re-evaluated from the current message on every turn. + # A previous high-risk turn used to stick permanently (issue #5): + # any follow-up, even an unrelated question, kept returning the + # emergency text with no retrieval. The earlier high-risk turn is + # still preserved in ``risk_history`` and surfaced as a brief + # reminder by ``draft``; only the live level/flags/advice follow + # the current message. assessment = self.safety.screen(state.get("normalized_message", ""), state.get("profile", {})) - previous_level = state.get("risk_level") - previous_flags = list(state.get("risk_flags", [])) - sticky_high = previous_level == "high" - if sticky_high or assessment.level == "high": + if assessment.level == "high": state["risk_level"] = "high" - state["risk_flags"] = list(dict.fromkeys(previous_flags + list(assessment.flags))) + state["risk_flags"] = list(assessment.flags) state["risk_advice"] = ( - "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。" + "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。" ) - elif previous_level == "watch" or assessment.level == "watch": + elif assessment.level == "watch": state["risk_level"] = "watch" - state["risk_flags"] = list(dict.fromkeys(previous_flags + list(assessment.flags))) + state["risk_flags"] = list(assessment.flags) state["risk_advice"] = assessment.advice else: state["risk_level"] = assessment.level @@ -609,7 +613,7 @@ def risk(self, state: WorkflowState) -> WorkflowState: "at": datetime.now(timezone.utc).isoformat(), "level": state["risk_level"], "flags": list(state.get("risk_flags", [])), - "source": "sticky-history" if sticky_high else "rules", + "source": "rules", } ) state["risk_history"] = history[-20:] @@ -709,6 +713,18 @@ def draft(self, state: WorkflowState) -> WorkflowState: state["next_question"] = missing if missing and state.get("risk_level") != "high" and not state.get("structured_result"): response += f"\n\n为了缩小分流范围,下一步想确认:{missing}" + if state.get("risk_level") != "high": + # First normal turn after an emergency turn: keep a brief + # reminder so the earlier emergency is not silently forgotten, + # without locking the session in emergency mode (issue #5). + history = list(state.get("risk_history", [])) + if len(history) >= 2 and history[-2].get("level") == "high" and history[-1].get("level") != "high": + prior_flags = [str(flag) for flag in history[-2].get("flags", []) if str(flag).strip()][:2] + if prior_flags: + response += ( + f"\n\n提醒:如之前出现的{'、'.join(prior_flags)}再次出现或加重," + "请立即拨打 120 或前往最近的急诊。" + ) state["response"] = response return state @@ -774,7 +790,9 @@ def safety_review(self, state: WorkflowState) -> WorkflowState: state["safety_blocked"] = True state["safety_block_reason"] = "unsafe-medical-instruction" return state - if "不代表诊断" not in response and state.get("risk_level") != "high": + if "不代表诊断" not in response: + # The disclaimer applies to emergency answers too (issue #5); + # it used to be skipped whenever the risk level was high. response += "\n\n提示:MedGuide 不替代医生诊断或处方。" state["response"] = response state["safety_blocked"] = False diff --git a/backend/tests/test_emergency_unlock.py b/backend/tests/test_emergency_unlock.py new file mode 100644 index 0000000..c0cb4e6 --- /dev/null +++ b/backend/tests/test_emergency_unlock.py @@ -0,0 +1,105 @@ +"""Issue #5: after an emergency turn the session must not stay locked in +emergency mode. Risk is re-evaluated from each message: unrelated +follow-up questions get normal answers (with retrieval), the earlier +high-risk turn is kept in ``risk_history`` and shown as a brief reminder +on the first normal turn, and a new high-risk message re-enters the +emergency flow. +""" + +from __future__ import annotations + +from app.retrieval import HybridRetriever +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow + +EMERGENCY_PREFIX = "当前描述包含需要优先排除的风险信号" + + +def _workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +def _emergency_turn() -> dict: + return _workflow().run( + { + "session_id": "emergency-unlock", + "user_message": "胸口突然剧烈疼痛,呼吸困难怎么办?", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + + +def test_emergency_response_names_120_and_carries_disclaimer() -> None: + first = _emergency_turn() + + assert first["risk_level"] == "high" + assert "120" in first["response"] + assert "不替代医生诊断或处方" in first["response"] + + +def test_drug_question_after_emergency_is_answered_normally() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + + assert first["risk_level"] == "high" + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) + assert second["citations"], "a normal follow-up should retrieve references again" + # The earlier emergency is not forgotten: history keeps it and the + # answer carries a brief reminder. + assert [entry["level"] for entry in second["risk_history"]].count("high") == 1 + assert "再次出现" in second["response"] + + +def test_unrelated_question_after_emergency_is_answered_normally() -> None: + first = _emergency_turn() + second = _workflow().run({**first, "user_message": "今天天气怎么样"}) + + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) + + +def test_emergency_recurs_when_high_risk_signals_return() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + assert second["risk_level"] == "low" + third = _workflow().run({**second, "user_message": "胸痛又发作了,呼吸困难"}) + + assert third["risk_level"] == "high" + assert third["citations"] == [] + assert third["response"].startswith(EMERGENCY_PREFIX) + assert "120" in third["response"] + assert [entry["level"] for entry in third["risk_history"]].count("high") == 2 + + +def test_reminder_only_on_first_turn_after_emergency() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + assert "再次出现" in second["response"] + third = _workflow().run({**second, "user_message": "今天天气怎么样"}) + + assert third["risk_level"] == "low" + assert "再次出现" not in third["response"] + + +def test_watch_level_is_reevaluated_too() -> None: + workflow = _workflow() + first = workflow.run( + { + "session_id": "watch-reevaluate", + "user_message": "发热38度", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert first["risk_level"] == "watch" + second = workflow.run({**first, "user_message": "今天天气怎么样"}) + + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) diff --git a/backend/tests/test_workflow_and_safety_regressions.py b/backend/tests/test_workflow_and_safety_regressions.py index ac12062..3c8ec73 100644 --- a/backend/tests/test_workflow_and_safety_regressions.py +++ b/backend/tests/test_workflow_and_safety_regressions.py @@ -24,7 +24,13 @@ def make_workflow(*, answerer: OpenAIAnswerer | None = None) -> MedGuideWorkflow return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine(), answerer) -def test_high_risk_is_sticky_across_follow_up_turns() -> None: +def test_high_risk_is_reevaluated_on_follow_up_turns() -> None: + # Behaviour change for issue #5: a high-risk turn used to lock the + # whole session in emergency mode, so every follow-up -- even an + # unrelated question -- returned the same emergency text with no + # retrieval. Risk is now re-evaluated from each message; the earlier + # high-risk turn is kept in ``risk_history`` and surfaced as a brief + # reminder instead of locking the session. workflow = make_workflow() first = workflow.run( { @@ -37,10 +43,10 @@ def test_high_risk_is_sticky_across_follow_up_turns() -> None: second = workflow.run(first) assert first["risk_level"] == "high" - assert second["risk_level"] == "high" - assert "胸痛或胸部压榨感" in second["risk_flags"] - assert second["citations"] == [] - assert "急诊" in second["response"] + assert second["risk_level"] == "low" + assert not second["response"].startswith("当前描述包含需要优先排除的风险信号") + assert "再次出现" in second["response"] + assert [entry["level"] for entry in second["risk_history"]].count("high") == 1 class _FakeCompletions: From a9d02539a4b2099a41bc17afec204f959d7a8e39 Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Wed, 18 Nov 2026 21:08:47 +0800 Subject: [PATCH 2/2] Rebase fix for #5 onto fix/issue-4-info-extraction --- backend/app/main.py | 28 +++++ backend/app/models.py | 6 + backend/app/store.py | 89 ++++++++++++++ backend/app/workflow.py | 131 ++++++++++++++++++++- backend/tests/test_info_extraction.py | 152 ++++++++++++++++++++++++ backend/tests/test_session_history.py | 159 +++++++++++++++++++++++++ frontend/src/App.tsx | 160 ++++++++++++++++++++++++-- frontend/src/styles.css | 1 + 8 files changed, 715 insertions(+), 11 deletions(-) create mode 100644 backend/tests/test_info_extraction.py create mode 100644 backend/tests/test_session_history.py diff --git a/backend/app/main.py b/backend/app/main.py index 217a42a..90c3003 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1022,6 +1022,34 @@ def create_session( return SessionCreateResponse(session_id=state["session_id"], state=public_state(state)) +@app.get("/api/sessions") +def list_sessions( + http_request: Request, + authorization: str | None = Header(default=None), + api_key: str | None = Header(default=None, alias="X-API-Key"), +) -> dict[str, Any]: + # Registered before /api/sessions/{session_id} so "sessions" is never + # treated as a session id. + current = get_services() + owner_id = _require_access( + current, + http_request, + authorization, + api_key, + _session_token_from_request(current, http_request), + ) + try: + sessions = current.store.list_sessions(owner_id) + except SessionBackendError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + return { + "sessions": sessions, + # False when the shared backend cannot enumerate sessions; the list + # is then empty on purpose rather than partial. See store.py. + "complete": current.store.listing_complete, + } + + @app.get("/api/sessions/{session_id}") def get_session( session_id: str, diff --git a/backend/app/models.py b/backend/app/models.py index 7ae75c6..22a452b 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -12,6 +12,7 @@ class PatientProfile(TypedDict, total=False): age: int sex: str duration: str + temperature: str symptoms: list[str] associated_symptoms: list[str] history: str @@ -24,6 +25,11 @@ class WorkflowState(TypedDict, total=False): owner_id: str user_message: str normalized_message: str + # Full turn transcript for this session, oldest first. Each entry is + # plain text plus identifiers only: {"role": "user" | "assistant", + # "content": str, "response_id": str (assistant only), "timestamp": str}. + # No passwords, cookies, or tokens are ever stored here. + messages: list[dict[str, Any]] profile: PatientProfile intent: Intent risk_level: RiskLevel diff --git a/backend/app/store.py b/backend/app/store.py index 52d06b0..b562de6 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -170,6 +170,7 @@ def create(self, owner_id: str | None = None, idempotency_key: str | None = None "_version": 0, "mode": self.mode, "events": [], + "messages": [], "citations": [], "risk_flags": [], "risk_assessed": False, @@ -362,9 +363,97 @@ def request_result(self, session_id: str, request_id: str, owner_id: str | None result = state.get("request_results", {}).get(request_id) return merge_request_result(state, result) if isinstance(result, dict) else None + @property + def listing_complete(self) -> bool: + """Whether :meth:`list_sessions` can enumerate every session. + + The in-memory store can. A shared Redis backend cannot be enumerated + (there is no session index), so listing is incomplete by design and + :meth:`list_sessions` returns ``[]`` rather than a partial list. + """ + if self.backend is None: + return True + return callable(getattr(self.backend, "list_states", None)) + + @staticmethod + def _session_list_entry(state: WorkflowState) -> dict[str, Any]: + messages = state.get("messages", []) or [] + first_user = next( + ( + str(item.get("content", "")).strip() + for item in messages + if isinstance(item, dict) + and item.get("role") == "user" + and str(item.get("content", "")).strip() + ), + "", + ) + title = first_user[:30] or str(state.get("summary", "") or "") or "新的健康咨询" + return { + "session_id": state.get("session_id"), + "title": title, + "summary": state.get("summary", ""), + "turn_count": int(state.get("turn_count", 0)), + "updated_at": state.get("updated_at"), + "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, + } + + def list_sessions(self, owner_id: str | None = None) -> list[dict[str, Any]]: + """Return one owner's unexpired sessions, newest first. + + Only the in-memory store can enumerate sessions. When a shared + backend is selected and it offers no ``list_states`` enumeration, + this returns ``[]`` (see :attr:`listing_complete`) instead of a + misleading partial list. + """ + owner = str(owner_id or "") + if self.backend is not None: + listing = getattr(self.backend, "list_states", None) + if not callable(listing): + return [] + try: + remote_states = listing(owner) + except Exception as exc: + raise SessionBackendError("共享会话后端暂时不可用,请稍后重试") from exc + states = [ + state + for state in (remote_states or []) + if isinstance(state, dict) and str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + with self._lock: + self._purge_expired() + states = [ + deepcopy(state) + for state in self._sessions.values() + if str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + + @staticmethod + def _public_messages(state: WorkflowState) -> list[dict[str, Any]]: + """Return only the transcript fields the API may expose.""" + messages: list[dict[str, Any]] = [] + for item in state.get("messages", []) or []: + if not isinstance(item, dict) or item.get("role") not in {"user", "assistant"}: + continue + entry: dict[str, Any] = { + "role": item["role"], + "content": str(item.get("content", "")), + } + if item.get("response_id"): + entry["response_id"] = str(item["response_id"]) + if item.get("timestamp"): + entry["timestamp"] = str(item["timestamp"]) + messages.append(entry) + return messages + def public(self, state: WorkflowState) -> dict: return { "session_id": state.get("session_id"), + "messages": self._public_messages(state), "turn_count": state.get("turn_count", 0), "profile": state.get("profile", {}), "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 2a63b74..df548b1 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -376,9 +376,17 @@ def normalize(self, state: WorkflowState) -> WorkflowState: state["normalized_message"] = re.sub(r"\s+", " ", message) return state + # Colloquial variants sit next to their written form. Keep the user's + # own wording (``发烧`` rather than normalising to ``发热``) so the + # profile panel shows what was actually said; ingestion already uses + # the same vocabulary (see ``ingestion._EMBEDDING_QUERY_TERMS``). _PROFILE_SYMPTOMS = ( - "发热", "咳嗽", "咽痛", "腹痛", "头痛", "胸痛", "皮疹", "头晕", "恶心", "呕吐", "乏力", - "流鼻涕", "流涕", "鼻塞", "呼吸困难", "气促", + "发热", "发烧", "高烧", "低热", "咳嗽", "咽痛", "喉咙痛", "喉咙疼", + "嗓子疼", "嗓子痛", "腹痛", "肚子痛", "肚子疼", "头痛", "头疼", + "胸痛", "胸闷", "皮疹", "瘙痒", "头晕", "恶心", "呕吐", "乏力", + "疲劳", "累", "流鼻涕", "流涕", "鼻塞", "呼吸困难", "气促", "气短", + "腹泻", "便秘", "心悸", "失眠", "睡眠不好", "睡不好", "耳鸣", "耳痛", + "水肿", "腰痛", "关节痛", "牙痛", "感冒", "流感", ) _PROFILE_SPLIT = re.compile(r"[,,。;;!?!?]|但是|可是|然而|但") _PROFILE_THIRD_PARTY = re.compile( @@ -401,8 +409,27 @@ def normalize(self, state: WorkflowState) -> WorkflowState: r"(?P\d{1,4}|[零〇一二两三四五六七八九十百]+|半)\s*" r"(?P分钟|小时|天|周|个月|月|年)" ) - _DURATION_PREFIX = re.compile(r"(?:持续|已经|已有|大约|约|大概|差不多)\s*$") + _DURATION_PREFIX = re.compile(r"(?:持续|已经|已有|大约|约|大概|差不多|最近)\s*$") _DURATION_NEGATION = re.compile(r"(?:不是|并非|没有|没|否认|不到|不足|不满)\s*$") + # Body temperature, mirroring the range already used by ingestion + # (35-42.x degrees). Stored as e.g. ``38.5度``. + _TEMPERATURE = re.compile( + r"(?(?:3[5-9]|4[0-2])(?:\.\d{1,2})?)\s*(?:摄氏度|℃|°C|度)" + ) + # Relative onset (``昨天开始``) only yields a duration when no numeric + # duration is known yet, so a later turn never overwrites an earlier, + # more precise one (e.g. fever for 3 days, sore throat since yesterday). + _RELATIVE_ONSET = {"大前天": "3天", "前天": "2天", "昨天": "1天"} + _RELATIVE_ONSET_PATTERN = re.compile(r"(?:从)?(大前天|前天|昨天)(?:开始|起|就|才)?") + _CHRONIC_CONDITIONS = ( + "慢性病", "基础疾病", "基础病", "重大疾病", "高血压", "糖尿病", "心脏病", "哮喘", + ) + # Symptom spellings with filler words in between (``睡眠也不好`` for + # ``睡眠不好``). Tuple lookup is substring-based, so these need a + # pattern instead; negation is checked the same way as for plain terms. + _PROFILE_SYMPTOM_PATTERNS = { + "睡眠不好": re.compile(r"睡(?:眠)?(?:也|都)?不好"), + } _DURATION_MAXIMUM = { "分钟": 10080, "小时": 8760, @@ -501,6 +528,13 @@ def _extract_duration(cls, clause: str) -> str | None: return f"{numeric}{unit}" return None + @classmethod + def _extract_relative_onset(cls, clause: str) -> str | None: + match = cls._RELATIVE_ONSET_PATTERN.search(clause) + if not match: + return None + return cls._RELATIVE_ONSET.get(match.group(1)) + def extract_profile(self, state: WorkflowState) -> WorkflowState: profile: PatientProfile = dict(state.get("profile", {})) text = state.get("normalized_message", "") @@ -536,10 +570,23 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if age_match: profile["age"] = int(age_match.group(1)) break + duration_found = False for clause in patient_clauses: duration = self._extract_duration(clause) if duration: profile["duration"] = duration + duration_found = True + break + if not duration_found and not profile.get("duration"): + for clause in patient_clauses: + onset = self._extract_relative_onset(clause) + if onset: + profile["duration"] = onset + break + for clause in patient_clauses: + temperature_match = self._TEMPERATURE.search(clause) + if temperature_match: + profile["temperature"] = f"{temperature_match.group('value')}度" break symptoms = list(profile.get("symptoms", [])) @@ -547,6 +594,14 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if any(self._asserted_profile_term(clause, symptom) for clause in patient_clauses): if symptom not in symptoms: symptoms.append(symptom) + for canonical, pattern in self._PROFILE_SYMPTOM_PATTERNS.items(): + if canonical in symptoms: + continue + for clause in patient_clauses: + match = pattern.search(clause) + if match and not self._PROFILE_NEGATION_BEFORE.search(clause[:match.start()]): + symptoms.append(canonical) + break profile["symptoms"] = symptoms if symptoms and not profile.get("chief_complaint"): profile["chief_complaint"] = symptoms[0] @@ -555,6 +610,28 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if history_match: profile["history"] = history_match.group(1).strip() break + # ``没有慢性病`` / ``无基础疾病``: the negated condition itself + # is the history, even though no ``病史`` noun follows it. + # Checked before the generic ``…病史`` rule so ``没有慢性病史`` + # becomes ``否认慢性病`` instead of the truncated ``否认慢性``. + chronic_pattern = "|".join(self._CHRONIC_CONDITIONS) + negative_chronic_match = re.search( + rf"(?:没有|无|否认)\s*({chronic_pattern})(?:史|等)?", + clause, + ) + if negative_chronic_match: + profile["history"] = f"否认{negative_chronic_match.group(1)}" + break + positive_chronic_match = re.search( + rf"(?:患有|有)\s*({chronic_pattern})(?:史|等)?", + clause, + ) + if positive_chronic_match and not re.search( + r"(?:没有|无|否认|不是|并非)", + clause[:positive_chronic_match.start()], + ): + profile["history"] = positive_chronic_match.group(1) + break negative_history_match = re.search( r"(?:没有|无|否认)\s*([^,。;;]{1,24}?)(?:等)?(?:既往病史|病史)", clause, @@ -743,6 +820,9 @@ def _external_query_summary(self, state: WorkflowState) -> str: duration = str(profile.get("duration", "")) if duration and re.fullmatch(r"[\d一二两三四五六七八九十半]+(?:分钟|小时|天|周|个月|月|年)", duration): parts.append(f"持续时间:{duration}") + temperature = str(profile.get("temperature", "")) + if temperature and re.fullmatch(r"(?:3[5-9]|4[0-2])(?:\.\d{1,2})?度", temperature): + parts.append(f"体温:{temperature}") associated = profile.get("associated_symptoms") if isinstance(associated, list): safe_associated = [item for item in associated if item in self._PROFILE_SYMPTOMS] @@ -768,7 +848,7 @@ def _next_question(profile: PatientProfile, risk_level: str, text: str) -> str | return "患者大致年龄是多少?" if not profile.get("duration"): return "症状从什么时候开始,持续了多久?" - if not profile.get("associated_symptoms") and any(word in text for word in ("发热", "咳嗽", "腹痛", "头痛", "皮疹")): + if not profile.get("associated_symptoms") and any(word in text for word in ("发热", "发烧", "咳嗽", "腹痛", "头痛", "头疼", "喉咙痛", "皮疹")): return "是否伴随发热、明显疼痛加重、呼吸困难或其他新出现的症状?" return None @@ -816,6 +896,46 @@ def _contains_unsafe_output(cls, response: str, compact_response: str) -> bool: return True return False + @staticmethod + def _append_turn_messages(state: WorkflowState) -> WorkflowState: + """Record this turn in the session transcript. + + Runs after ``safety_review``, so the assistant entry holds the final + reviewed response. Idempotent replays never reach this node (the + caller returns the stored result first), and ``response_id`` guards + against a duplicate append if a turn were ever executed twice. + """ + user_message = str(state.get("user_message") or state.get("normalized_message") or "").strip() + response = str(state.get("response", "") or "") + response_id = str(state.get("response_id") or "") + if not user_message and not response: + return state + messages = [ + dict(item) + for item in state.get("messages", []) or [] + if isinstance(item, dict) + ] + if response_id and any( + item.get("role") == "assistant" and item.get("response_id") == response_id + for item in messages + ): + return state + timestamp = datetime.now(timezone.utc).isoformat() + if user_message: + messages.append({"role": "user", "content": user_message, "timestamp": timestamp}) + if response: + assistant: dict[str, Any] = { + "role": "assistant", + "content": response, + "timestamp": timestamp, + } + if response_id: + assistant["response_id"] = response_id + messages.append(assistant) + # Bound transcript growth the same way response_ids are bounded. + state["messages"] = messages[-100:] + return state + def finalize(self, state: WorkflowState) -> WorkflowState: citations = state.get("citations", []) structured_result = state.get("structured_result") @@ -835,11 +955,14 @@ def finalize(self, state: WorkflowState) -> WorkflowState: summary_parts.append(str(profile["sex"])) if profile.get("symptoms"): summary_parts.append("主要症状:" + "、".join(profile["symptoms"][:4])) + if profile.get("temperature"): + summary_parts.append(f"体温{profile['temperature']}") if profile.get("duration"): summary_parts.append("持续" + str(profile["duration"])) if profile.get("history"): summary_parts.append("既往史:" + str(profile["history"])) state["summary"] = ";".join(summary_parts) if summary_parts else "已建立会话,等待补充症状和基础信息。" + self._append_turn_messages(state) # The runner writes its actual engine after the node loop completes. state.setdefault("workflow_engine", "deterministic") return state diff --git a/backend/tests/test_info_extraction.py b/backend/tests/test_info_extraction.py new file mode 100644 index 0000000..feafe55 --- /dev/null +++ b/backend/tests/test_info_extraction.py @@ -0,0 +1,152 @@ +"""Issue #4: key information (fever, duration, temperature, history) must be +extracted from colloquial user messages instead of being dropped.""" + +from app.retrieval import HybridRetriever +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow + + +def make_workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +def run_turn(workflow: MedGuideWorkflow, state: dict, text: str) -> dict: + state = dict(state) + state["user_message"] = text + return workflow.run(state) + + +def test_issue4_two_turn_conversation_extracts_fever_duration_temperature_history(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-main", "profile": {}}, + "我最近三天发烧38.5度,还咳嗽,应该怎么办?", + ) + profile = state["profile"] + assert "发烧" in profile["symptoms"] + assert "咳嗽" in profile["symptoms"] + assert profile["duration"] == "3天" + assert profile["temperature"] == "38.5度" + assert "体温38.5度" in state["summary"] + assert "持续3天" in state["summary"] + + state = run_turn(workflow, state, "今年25岁,没有慢性病,昨天开始喉咙痛") + profile = state["profile"] + assert profile["age"] == 25 + assert profile["history"] == "否认慢性病" + assert "喉咙痛" in profile["symptoms"] + # The sore throat started yesterday, but the earlier, more precise + # 3-day duration must not be overwritten by the relative onset. + assert profile["duration"] == "3天" + assert "喉咙痛" in profile["associated_symptoms"] + assert state["next_question"] != "症状从什么时候开始,持续了多久?" + assert "持续3天" in state["summary"] + assert "既往史:否认慢性病" in state["summary"] + + +def test_issue4_relative_onset_only_fills_missing_duration(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-onset", "profile": {}}, + "昨天开始喉咙痛", + ) + assert state["profile"]["duration"] == "1天" + assert "喉咙痛" in state["profile"]["symptoms"] + + +def test_issue4_short_colloquial_symptom_messages(): + workflow = make_workflow() + headache = run_turn( + workflow, {"session_id": "issue4-headache", "profile": {}}, "头疼" + ) + assert "头疼" in headache["profile"]["symptoms"] + + tired = run_turn( + workflow, + {"session_id": "issue4-tired", "profile": {}}, + "最近总觉得累,睡眠也不好", + ) + assert "累" in tired["profile"]["symptoms"] + assert "睡眠不好" in tired["profile"]["symptoms"] + + +def test_issue4_colloquial_variants_and_temperature_spellings(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-variants", "profile": {}}, + "我发烧了,体温38.5℃,嗓子疼", + ) + profile = state["profile"] + assert "发烧" in profile["symptoms"] + assert "嗓子疼" in profile["symptoms"] + assert profile["temperature"] == "38.5度" + + state = workflow.extract_profile( + {"normalized_message": "我有高血压", "profile": {}} + ) + assert state["profile"]["history"] == "高血压" + + +def test_issue4_negated_or_third_party_symptoms_still_excluded(): + workflow = make_workflow() + negated = run_turn( + workflow, + {"session_id": "issue4-negated", "profile": {}}, + "我没有发烧,也没有咳嗽", + ) + assert negated["profile"]["symptoms"] == [] + + third_party = run_turn( + workflow, + {"session_id": "issue4-third-party", "profile": {}}, + "我妈妈发烧咳嗽,我想问问怎么办", + ) + assert third_party["profile"]["symptoms"] == [] + + coordinated = workflow.extract_profile( + { + "normalized_message": "咳嗽,已经三天,没有胸痛或呼吸困难", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert coordinated["profile"]["symptoms"] == ["咳嗽"] + + denied_history = workflow.extract_profile( + {"normalized_message": "否认有糖尿病", "profile": {}} + ) + assert denied_history["profile"].get("history") != "糖尿病" + + +def test_issue4_duration_guards_still_hold(): + workflow = make_workflow() + for message in ("我32岁,咳嗽不是三天", "我2026年做过体检,最近咳嗽"): + state = workflow.extract_profile( + { + "normalized_message": message, + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert "duration" not in state["profile"] + + +def test_issue4_temperature_in_external_summary(): + workflow = make_workflow() + outbound = workflow._external_query_summary( + { + "intent": "disease", + "profile": { + "age": 25, + "chief_complaint": "发烧", + "duration": "3天", + "temperature": "38.5度", + }, + "risk_flags": [], + "citations": [], + } + ) + assert "体温:38.5度" in outbound + assert "持续时间:3天" in outbound diff --git a/backend/tests/test_session_history.py b/backend/tests/test_session_history.py new file mode 100644 index 0000000..2ca78a7 --- /dev/null +++ b/backend/tests/test_session_history.py @@ -0,0 +1,159 @@ +"""Session history (issue #3): transcript persistence and listing. + +Covers: multi-turn messages stored and restored via GET, the session list +being newest-first and owner-scoped, cross-user reads returning 404, +expired sessions excluded from the list, and idempotent replay not +duplicating transcript entries. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient + +import app.main as main_module +from app.main import AppServices, app +from app.store import SessionStore + + +@pytest.fixture() +def services(tmp_path, monkeypatch): + """A fresh, isolated AppServices (fresh store + fresh auth DB).""" + monkeypatch.setenv("MEDGUIDE_AUTH_DB_PATH", str(tmp_path / "auth.sqlite3")) + current = AppServices() + monkeypatch.setattr(main_module, "get_services", lambda: current) + yield current + current.close() + + +@pytest.fixture() +def client(services): + with TestClient(app, base_url="https://testserver") as test_client: + yield test_client + + +def _register(client: TestClient, username: str) -> None: + response = client.post( + "/api/auth/register", + json={"username": username, "password": "Correct-Horse-42"}, + ) + assert response.status_code == 201 + + +def _chat(client: TestClient, session_id: str, message: str, request_id: str): + response = client.post( + "/api/chat", + json={"session_id": session_id, "message": message, "request_id": request_id}, + ) + assert response.status_code == 200 + return response.json() + + +def test_multi_turn_messages_persist_and_restore_via_get(client: TestClient) -> None: + # Issue #6 requires a session for /api/sessions in every mode. + _register(client, "history_multi_turn") + session_id = client.post("/api/sessions").json()["session_id"] + first = _chat(client, session_id, "我32岁,咳嗽持续3天", "turn-history-0001") + second = _chat(client, session_id, "还伴随发热38度", "turn-history-0002") + + state = client.get(f"/api/sessions/{session_id}").json() + assert state["turn_count"] == 2 + messages = state["messages"] + assert [item["role"] for item in messages] == ["user", "assistant", "user", "assistant"] + assert messages[0]["content"] == "我32岁,咳嗽持续3天" + assert messages[2]["content"] == "还伴随发热38度" + assert messages[1]["content"] == first["answer"] + assert messages[3]["content"] == second["answer"] + assert messages[1]["response_id"] == first["response_id"] + assert messages[3]["response_id"] == second["response_id"] + assert all(item.get("timestamp") for item in messages) + + +def test_session_list_is_newest_first_and_owner_scoped(client: TestClient) -> None: + alice = client + _register(alice, "history_alice") + first_id = alice.post("/api/sessions").json()["session_id"] + _chat(alice, first_id, "我咳嗽三天", "turn-list-a-0001") + second_id = alice.post("/api/sessions").json()["session_id"] + _chat(alice, second_id, "我想查布洛芬库存", "turn-list-a-0002") + + bob = TestClient(app, base_url="https://testserver") + try: + _register(bob, "history_bob") + other_id = bob.post("/api/sessions").json()["session_id"] + _chat(bob, other_id, "我头痛", "turn-list-b-0001") + + listed = alice.get("/api/sessions").json() + assert listed["complete"] is True + sessions = listed["sessions"] + assert [item["session_id"] for item in sessions] == [second_id, first_id] + assert sessions[0]["title"] == "我想查布洛芬库存" + assert sessions[1]["title"] == "我咳嗽三天" + assert sessions[0]["turn_count"] == 1 + assert all(item["session_id"] != other_id for item in sessions) + + bob_listed = bob.get("/api/sessions").json() + assert [item["session_id"] for item in bob_listed["sessions"]] == [other_id] + finally: + bob.close() + + +def test_cross_user_session_read_returns_404(client: TestClient) -> None: + _register(client, "history_owner") + session_id = client.post("/api/sessions").json()["session_id"] + _chat(client, session_id, "我咳嗽三天", "turn-cross-0001") + + stranger = TestClient(app, base_url="https://testserver") + try: + _register(stranger, "history_stranger") + assert stranger.get(f"/api/sessions/{session_id}").status_code == 404 + assert stranger.get("/api/sessions").json()["sessions"] == [] + finally: + stranger.close() + + +def test_idempotent_replay_does_not_duplicate_messages(client: TestClient) -> None: + # Issue #6 requires a session for /api/sessions in every mode. + _register(client, "history_replay") + session_id = client.post("/api/sessions").json()["session_id"] + request = { + "session_id": session_id, + "message": "我32岁,咳嗽持续3天", + "request_id": "turn-replay-0001", + } + first = client.post("/api/chat", json=request) + replay = client.post("/api/chat", json=request) + assert first.status_code == replay.status_code == 200 + assert replay.json()["response_id"] == first.json()["response_id"] + + state = client.get(f"/api/sessions/{session_id}").json() + assert state["turn_count"] == 1 + assert len(state["messages"]) == 2 + assert [item["role"] for item in state["messages"]] == ["user", "assistant"] + + +def test_new_session_public_state_has_empty_messages() -> None: + store = SessionStore(mode="test") + state = store.create(owner_id="user:someone") + assert store.public(state)["messages"] == [] + assert store.list_sessions("user:someone")[0]["title"] == "新的健康咨询" + + +def test_expired_sessions_are_excluded_from_list() -> None: + now = [1_000.0] + store = SessionStore(mode="test", ttl_seconds=60, clock=lambda: now[0]) + old_id = store.create(owner_id="user:alice")["session_id"] + now[0] = 1_050.0 + new_id = store.create(owner_id="user:alice")["session_id"] + now[0] = 1_070.0 + assert store.get(old_id) is None + listed = store.list_sessions("user:alice") + assert [item["session_id"] for item in listed] == [new_id] + + +def test_redis_backend_list_is_empty_and_marked_incomplete() -> None: + store = SessionStore(backend=SimpleNamespace(), mode="production") + assert store.listing_complete is False + assert store.list_sessions("user:alice") == [] diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..856dd58 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -53,6 +53,13 @@ type Citation = { source_url?: string; }; +type StoredMessage = { + role: "user" | "assistant"; + content: string; + response_id?: string; + timestamp?: string; +}; + type SessionState = { session_id: string; turn_count: number; @@ -62,6 +69,8 @@ type SessionState = { intent: string; next_question: string | null; mode: string; + /** Full turn transcript, oldest first; absent on older API versions. */ + messages?: StoredMessage[]; /** Optional capability fields supplied by newer API versions. */ environment?: string; network_enabled?: boolean; @@ -73,6 +82,15 @@ type SessionState = { summary?: string; }; +type SessionListItem = { + session_id: string; + title: string; + summary: string; + turn_count: number; + updated_at: string | null; + risk_level?: RiskLevel | null; +}; + type StructuredResult = { intent: string; sql: string; @@ -246,6 +264,7 @@ function App() { const [authBootstrapError, setAuthBootstrapError] = useState(null); const [logoutPending, setLogoutPending] = useState(false); const [session, setSession] = useState(null); + const [sessions, setSessions] = useState([]); const [messages, setMessages] = useState([initialMessage]); const [draft, setDraft] = useState(""); const [loading, setLoading] = useState(false); @@ -403,6 +422,7 @@ function App() { committedResponseIdsRef.current.clear(); sessionCreateKeyRef.current = null; setSession(null); + setSessions([]); setSessionStatus("idle"); setMessages([{ ...initialMessage, timestamp: Date.now() }]); setDraft(""); @@ -436,7 +456,117 @@ function App() { setAuthBootstrapError(null); const createKey = createRequestId("session"); sessionCreateKeyRef.current = createKey; - startSession(createKey); + void loadSessionHistory(); + } + + /** Best-effort refresh of the left-rail history list; never blocks chat. */ + async function refreshSessionList() { + try { + const response = await apiFetch("/api/sessions"); + if (!response.ok) return; + const body = (await response.json()) as { sessions?: SessionListItem[] }; + if (Array.isArray(body.sessions)) setSessions(body.sessions); + } catch { + // History is a convenience view; a failed refresh must not surface + // as a chat error. + } + } + + /** + * On login/refresh, restore the newest session that already has messages + * instead of opening an empty one. A fresh session is created only when + * the user has no history yet. The list endpoint — not localStorage — + * is the source of truth for which sessions exist. + */ + async function loadSessionHistory() { + const generation = generationRef.current; + setSessionStatus("creating"); + try { + const response = await apiFetch("/api/sessions"); + await ensureResponseOk(response); + const body = (await response.json()) as { sessions?: SessionListItem[] }; + const listed = Array.isArray(body.sessions) ? body.sessions : []; + if (generationRef.current !== generation) return; + setSessions(listed); + const latest = listed.find((item) => item.turn_count > 0); + if (latest) { + await restoreSession(latest.session_id); + return; + } + } catch (requestError) { + if (generationRef.current !== generation) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + // Fall through to a fresh session when history cannot be read. + } + startSession(sessionCreateKeyRef.current || createRequestId("session")); + } + + function applyRestoredSession(state: SessionState) { + activeSessionIdRef.current = state.session_id; + committedResponseIdsRef.current.clear(); + const restored: Message[] = [{ ...initialMessage, timestamp: Date.now() }]; + for (const [index, item] of (state.messages || []).entries()) { + const parsed = item.timestamp ? Date.parse(item.timestamp) : Number.NaN; + const message: Message = { + id: item.response_id || `restored-${index}`, + role: item.role, + content: item.content, + timestamp: Number.isNaN(parsed) ? Date.now() : parsed, + sessionId: state.session_id, + }; + if (item.role === "assistant" && item.response_id) { + committedResponseIdsRef.current.add(item.response_id); + } + restored.push(message); + } + setSession(state); + setMessages(restored); + // Per-message citations are not stored server-side, so restored + // answers link no references; the live turn's citations still apply. + setCitations([]); + setSelectedCitationMessageId(null); + setStructuredResult(null); + setEvents([]); + setFeedbackSent({}); + setFeedbackPending({}); + } + + async function restoreSession(sessionId: string) { + const generation = ++generationRef.current; + sessionRequestRef.current?.abort(); + chatRequestRef.current?.abort(); + chatRequestRef.current = null; + pendingRetryRef.current = null; + setSessionStatus("creating"); + setLoading(false); + setError(null); + const controller = new AbortController(); + sessionRequestRef.current = controller; + try { + const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`, { + signal: controller.signal, + }); + await ensureResponseOk(response); + const body = (await response.json()) as SessionState; + if (!body.session_id || !requestIsCurrent(generation, controller)) return; + applyRestoredSession(body); + setSessionStatus("ready"); + } catch (requestError) { + if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + activeSessionIdRef.current = null; + setSession(null); + setSessionStatus("error"); + setError(requestError instanceof HttpResponseError ? formatHttpError(requestError) : "整理服务暂不可用,请稍后重试。"); + } finally { + if (sessionRequestRef.current === controller) sessionRequestRef.current = null; + } } function restoreAuthentication() { @@ -578,6 +708,7 @@ function App() { activeSessionIdRef.current = body.state.session_id; setSession(body.state); setSessionStatus("ready"); + void refreshSessionList(); } catch (requestError) { if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; if (requestError instanceof HttpResponseError && requestError.status === 401) { @@ -773,6 +904,8 @@ function App() { latency: body.latency_ms, sessionId: body.state.session_id, }); + // The turn changed this session's title and turn count in the history. + void refreshSessionList(); } function newConversation() { @@ -922,12 +1055,25 @@ function App() { -
这次对话
+
历史对话
- + {sessions.length === 0 ? ( + + ) : ( + sessions.map((item) => ( + + )) + )}
如何描述问题 @@ -1025,7 +1171,7 @@ function App() {
{riskAssessed ? "随补充信息重新筛查" : "等待首次描述"}
- {isWelcome ?

聊之前,可以想一想

  1. 01
    最在意的感受

    哪里不舒服?与平时有什么不同?

  2. 02
    发生的时间

    什么时候开始,有没有变得更明显?

  3. 03
    你想弄清的事

    用药、检查,还是该去哪个科室?

:
已提供的信息

已经了解的情况

{session?.summary &&
整理摘要

{session.summary}

}{session?.next_question &&

还可以补充{session.next_question}

}
} + {isWelcome ?

聊之前,可以想一想

  1. 01
    最在意的感受

    哪里不舒服?与平时有什么不同?

  2. 02
    发生的时间

    什么时候开始,有没有变得更明显?

  3. 03
    你想弄清的事

    用药、检查,还是该去哪个科室?

:
已提供的信息

已经了解的情况

{session?.summary &&
整理摘要

{session.summary}

}{session?.next_question &&

还可以补充{session.next_question}

}
} {!isWelcome &&
本次整理{session?.workflow_version ? ` · ${session.workflow_version}` : ""}

处理进度

{events.length || loading ?
{buildWorkflowStages(events, risk, session?.intent, loading).map((stage, index) =>
{stage.status === "completed" ? : index + 1}
{stage.label}{stage.detail && {stage.detail}}
{stage.status === "completed" ? "完成" : stage.status === "skipped" ? "跳过" : stage.status === "running" ? "进行中" : "待处理"}
)}
:

回答已完成,未返回详细流程。

}
} diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 2523191..3f9cb9e 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -139,6 +139,7 @@ button.starter-prompt:hover:not(:disabled) { border-color:#a1cbd0; background:#f .conversation-list { display:grid; gap:4px; } .conversation-item { display:flex; align-items:center; gap:8px; width:100%; padding:11px 8px; color:var(--ink-800); text-align:left; background:var(--teal-050); border:1px solid #d0e5e8; border-radius:7px; } .conversation-item:hover { background:#e8f3f5; } +.conversation-item.active { background:#e8f3f5; border-color:#b6dadd; } .conversation-icon { display:grid; place-items:center; flex-shrink:0; width:24px; color:var(--teal-700); } .conversation-copy { display:grid; gap:5px; min-width:0; } .conversation-copy strong { overflow:hidden; font-size:12px; font-weight:500; text-overflow:ellipsis; white-space:nowrap; }