Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 48 additions & 8 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,9 +565,13 @@ def _require_access(
# A proxy-validated cookie can expire or be revoked before this handler.
# Cookie-bearing offline requests must not fall back to anonymous access;
# production service-header priority remains unchanged.
if principal is None and (
getattr(current, "production", False) or getattr(current, "local", False) or session_token is not None
):
# Issue #6: authentication is required in every mode. Test/offline used
# to let requests without any credential through (while rejecting an
# invalid cookie), which exposed protected APIs and other users'
# sessions anonymously. There is intentionally no anonymous fallback
# switch: /api/health and /api/ready stay public for probes, and every
# other caller must present a valid session cookie or service token.
if principal is None:
raise HTTPException(status_code=401, detail="请先登录")
_require_runtime(current)
return principal
Expand All @@ -580,11 +584,19 @@ def _require_service_access(
api_key: str | None = None,
) -> str | None:
_require_secure_transport(current, request)
if not current.production:
return None
principal = _principal_from_headers(current, authorization, api_key)
_require_runtime(current)
return principal
if current.production:
principal = _principal_from_headers(current, authorization, api_key)
_require_runtime(current)
return principal
# Issue #6: the operator endpoint was wide open outside production
# (this function returned before any check). No service API tokens are
# configured in test/offline/local modes, so a logged-in user session is
# the credential here; anonymous access is never allowed. Production
# keeps the stricter service-token-only rule.
username = _username_from_cookie(current, _session_token_from_request(current, request))
if username is None:
raise HTTPException(status_code=401, detail="请先登录")
return f"user:{username}"


def _message_fingerprint(message: str) -> str:
Expand Down Expand Up @@ -1022,6 +1034,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,
Expand Down
6 changes: 6 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
57 changes: 55 additions & 2 deletions backend/app/retrieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
import re
from pathlib import Path
from collections.abc import Mapping
from collections.abc import Iterable, Mapping
from time import monotonic
from typing import Any

Expand All @@ -18,7 +18,15 @@

class IntentRouter:
KEYWORDS: dict[Intent, tuple[str, ...]] = {
"drug": ("药", "用药", "剂量", "副作用", "禁忌", "服用"),
"drug": (
"药", "用药", "剂量", "副作用", "禁忌", "服用",
# How to take a medicine is a drug question even when the drug
# name itself is the only drug word in the sentence, e.g.
# "布洛芬怎么吃?有什么注意事项?" used to fall through to "faq"
# on "注意事项" and then retrieve nothing.
"怎么吃", "如何吃", "怎么服用", "如何服用", "吃法", "用法", "用量",
"能吃吗", "可以吃吗",
),
"exam": ("检查", "检验", "化验", "指标", "报告", "价格", "多少钱"),
"department": (
"科室", "挂什么号", "挂什么科", "挂哪个科", "看什么科", "去哪个科",
Expand All @@ -32,12 +40,24 @@ class IntentRouter:
"structured": ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用"),
}

def __init__(self, drug_names: Iterable[str] | None = None) -> None:
# Drug names are supplied by the caller (the workflow passes the
# names of the drug documents in the knowledge catalog). A bare
# router still works: the usage patterns in KEYWORDS["drug"] cover
# questions such as "布洛芬怎么吃".
self.drug_names = tuple(
dict.fromkeys(name.strip() for name in (drug_names or ()) if name and name.strip())
)

def classify(self, text: str) -> Intent:
normalized = text.lower()
structured = sum(1 for word in self.KEYWORDS["structured"] if word in normalized)
if structured and any(word in normalized for word in ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用")):
return "structured"
scores = {intent: sum(1 for word in words if word in normalized) for intent, words in self.KEYWORDS.items() if intent != "structured"}
for name in self.drug_names:
if name.lower() in normalized:
scores["drug"] = scores.get("drug", 0) + 1
best = max(scores, key=scores.get)
return best if scores[best] else "unknown"

Expand Down Expand Up @@ -163,6 +183,39 @@ def _load_documents(self) -> list[KnowledgeDocument]:
catalog = self.knowledge_dir / "catalog.json"
return load_catalog(catalog)

@property
def drug_names(self) -> tuple[str, ...]:
"""Drug-related terms from the drug documents in the catalog.

Tags are curated per document, but some are generic clinical words
(e.g. "过敏", "皮疹") that belong to symptoms or other intents, so
they are filtered out: only terms that are not part of the shared
clinical vocabulary and not a keyword of another intent may vote
for the drug intent.
"""
other_keywords = {
word
for intent, words in IntentRouter.KEYWORDS.items()
if intent != "drug"
for word in words
}
clinical_terms = set(MedicalDocumentCleaner._EMBEDDING_QUERY_TERMS)
# "止痛" and "退热" are effects, not drug names: as intent signals
# they would outvote the disease intent on symptom questions such
# as "发烧怎么退热" or "头痛怎么止痛".
effect_words = {"止痛", "退热"}
names = {
tag.strip()
for document in self.documents
if document.category == "drug"
for tag in document.tags
if tag and tag.strip()
and tag.strip() not in other_keywords
and tag.strip() not in clinical_terms
and tag.strip() not in effect_words
}
return tuple(sorted(names))

@staticmethod
def _cosine(left: list[float], right: list[float]) -> float:
return sum(a * b for a, b in zip(left, right))
Expand Down
2 changes: 1 addition & 1 deletion backend/app/safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
91 changes: 87 additions & 4 deletions backend/app/sql_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,14 +539,87 @@ def execute(self, intent: str, sql: str, params: tuple[Any, ...] = ()) -> SQLQue
)
return SQLQueryResult(intent, validated, params, (), (), blocked=True, reason=reason)

def _known_names(self, table: str) -> tuple[str, ...] | None:
"""Distinct entity names registered in a whitelisted table.

The names come from the table itself (the same data the LIKE
predicate searches), never from free text, so a lookup term can
only ever be an allowlisted value or one of its prefixes. Returns
``None`` when the list cannot be loaded (e.g. the data backend is
unavailable); callers then fall back to the legacy term extraction
instead of pretending the catalog is empty.
"""
if table not in self.TABLE_COLUMNS:
return None
column = self.TABLE_COLUMNS[table][0]
sql = f"SELECT DISTINCT {column} FROM {table}"
try:
if self.backend is not None:
ensure_ready = getattr(self.backend, "ensure_ready", None)
if callable(ensure_ready):
if not ensure_ready():
return None
elif not getattr(self.backend, "ready", False):
return None
_, rows = self.backend.execute(sql, ())
names = [str(row.get(column, "")) for row in rows]
else:
with sqlite3.connect(self.db_path) as conn:
names = [str(row[0]) for row in conn.execute(sql).fetchall()]
except Exception:
return None
return tuple(sorted({name.strip() for name in names if name and name.strip()}))

@staticmethod
def _match_known_term(text: str, known_names: tuple[str, ...]) -> str:
"""Longest registered entity name (or its longest known prefix) in text.

A full registered name wins; otherwise the longest prefix of a
registered name (at least 2 characters, e.g. "布洛芬" for
"布洛芬缓释胶囊") is used, so the LIKE predicate stays an
indexable prefix search. Returns "" when no registered name
matches, so the caller can ask for clarification instead of
running a lookup that is guaranteed to return zero rows.
"""
best = ""
for name in known_names:
if name and name in text and len(name) > len(best):
best = name
if best:
return best
for name in known_names:
for end in range(len(name), 1, -1):
prefix = name[:end]
if prefix in text:
if len(prefix) > len(best):
best = prefix
break
return best

@staticmethod
def _unregistered_term_reason(term: str, kind: str) -> str:
"""Clarification reason when the user named something unregistered.

``term`` is the legacy extraction of what the user wrote; it is
only echoed back when it is short and free of LIKE metacharacters,
otherwise the generic prompt for a specific name is used.
"""
if term and len(term) <= 24 and not any(ch in term for ch in ("%_", "\\")):
return f"未能识别出已登记的{kind}名称“{term}”,请确认名称是否正确,或提供完整的{kind}名称"
return f"请提供需要查询的具体{kind}名称"

def from_natural_language(self, text: str) -> SQLQueryResult | None:
normalized = text.strip()
if not any(word in normalized for word in ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用")):
return None
if self.unavailable_reason:
return SQLQueryResult("structured", "", (), (), (), blocked=True, reason=self.unavailable_reason)
if any(word in normalized for word in ("库存", "有货")):
drug = self._extract_term(normalized, ("库存", "有货", "药品"))
known = self._known_names("drug_inventory")
if known is not None:
drug = self._match_known_term(normalized, known)
else:
drug = self._extract_term(normalized, ("库存", "有货", "药品"))
if not drug:
return SQLQueryResult(
"drug_inventory",
Expand All @@ -555,7 +628,10 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None:
(),
(),
blocked=True,
reason="请提供需要查询的具体药品名称",
reason=self._unregistered_term_reason(
self._extract_term(normalized, ("库存", "有货", "药品")),
"药品",
),
)
sql = "SELECT name, stock, unit, updated_at FROM drug_inventory WHERE name LIKE ? ORDER BY stock DESC LIMIT 50"
return self.execute("drug_inventory", sql, (f"{drug}%",))
Expand All @@ -573,7 +649,11 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None:
)
sql = "SELECT doctor_name, department, date, shift, available_slots FROM doctor_schedules WHERE department LIKE ? ORDER BY date, shift LIMIT 50"
return self.execute("doctor_schedules", sql, (f"{department}%",))
exam = self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验"))
known = self._known_names("exam_prices")
if known is not None:
exam = self._match_known_term(normalized, known)
else:
exam = self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验"))
if not exam:
return SQLQueryResult(
"exam_prices",
Expand All @@ -582,7 +662,10 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None:
(),
(),
blocked=True,
reason="请提供需要查询的具体检查或检验名称",
reason=self._unregistered_term_reason(
self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验")),
"检查或检验",
),
)
sql = "SELECT test_name, price, department, notes FROM exam_prices WHERE test_name LIKE ? ORDER BY price LIMIT 50"
return self.execute("exam_prices", sql, (f"{exam}%",))
Expand Down
Loading