|
|
@@ -870,6 +870,250 @@ def _format_health_status(hs: dict) -> str:
|
|
|
return "; ".join(out)
|
|
|
|
|
|
|
|
|
+# 结构化知识库(本地治理表)上下文:与主 RAG 检索并行注入,失败一律静默降级。
|
|
|
+_KB_GOAL_KEYWORDS = {
|
|
|
+ "血糖": ("血糖", "糖化", "葡萄糖", "空腹血糖"),
|
|
|
+ "血脂": ("血脂", "胆固醇", "甘油三酯", "低密度", "高密度"),
|
|
|
+ "肥胖": ("肥胖", "体重", "BMI", "体质指数", "腰围"),
|
|
|
+ "便秘": ("便秘", "排便"),
|
|
|
+ "腹胀": ("腹胀", "胀气", "产气"),
|
|
|
+ "过敏": ("过敏", "IgE"),
|
|
|
+ "失眠": ("失眠", "睡眠"),
|
|
|
+ "抑郁": ("抑郁", "情绪", "焦虑", "压力"),
|
|
|
+}
|
|
|
+_KB_GOAL_MODULES = {
|
|
|
+ "血糖": ("CARBOMETAB",),
|
|
|
+ "血脂": ("LIPIDMET",),
|
|
|
+ "肥胖": ("CARBOMETAB", "LIPIDMET"),
|
|
|
+ "便秘": ("BARRIER",),
|
|
|
+ "腹胀": ("BARRIER", "SCFA"),
|
|
|
+ "过敏": ("IMMUNE",),
|
|
|
+ "失眠": ("NEURO",),
|
|
|
+ "抑郁": ("NEURO",),
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+def _kb_goal_ids_from_text(text: str, loader) -> list[str]:
|
|
|
+ """按知识库目标名及同义线索从文本中解析 goal_id。"""
|
|
|
+ content = str(text or "")
|
|
|
+ if not content:
|
|
|
+ return []
|
|
|
+ name_to_id = {g["goal_name"]: g["goal_id"] for g in loader.list_goals()}
|
|
|
+ matched = []
|
|
|
+ for name, goal_id in name_to_id.items():
|
|
|
+ keywords = (name,) + _KB_GOAL_KEYWORDS.get(name, ())
|
|
|
+ if any(keyword and keyword in content for keyword in keywords):
|
|
|
+ matched.append(goal_id)
|
|
|
+ return matched
|
|
|
+
|
|
|
+
|
|
|
+# 个性化食材加权榜(规范 §四)注入:仅取报告「疾病相关菌」区块作为方向源。
|
|
|
+_WEIGHTED_TOP_N = 8
|
|
|
+# Java 归一化别名兼容:后端可能把中文键转 snake_case,或嵌在 report/raw 子对象里。
|
|
|
+_DISEASE_RELATED_KEYS = ("疾病相关菌", "diseaseRelated", "disease_related", "diseaseRelatedBacteria")
|
|
|
+_DETAIL_WRAPPERS = ("report", "reportData", "raw")
|
|
|
+
|
|
|
+
|
|
|
+def _extract_disease_related(detail: dict) -> dict:
|
|
|
+ """从报告详情中抽取「疾病相关菌」区块(兼容 Java 归一化别名与嵌套包裹)。
|
|
|
+
|
|
|
+ 返回形如 {病名: [条目...]};找不到返回空 dict,调用方据此降级,不抛异常。
|
|
|
+ """
|
|
|
+ if not isinstance(detail, dict):
|
|
|
+ return {}
|
|
|
+ candidates = [detail]
|
|
|
+ for wrapper in _DETAIL_WRAPPERS:
|
|
|
+ inner = detail.get(wrapper)
|
|
|
+ if isinstance(inner, dict):
|
|
|
+ candidates.append(inner)
|
|
|
+ for candidate in candidates:
|
|
|
+ for key in _DISEASE_RELATED_KEYS:
|
|
|
+ value = candidate.get(key)
|
|
|
+ if value:
|
|
|
+ return value
|
|
|
+ return {}
|
|
|
+
|
|
|
+
|
|
|
+async def _member_weighted_foods(java: JavaClient, report_id, top_n: int = _WEIGHTED_TOP_N) -> dict | None:
|
|
|
+ """报告详情 → 「疾病相关菌」→ 三级加权食材榜(方案生成链路专用)。
|
|
|
+
|
|
|
+ 防御式:报告详情缺失、后端未补「疾病相关菌」字段、或计算降级时返回 None,
|
|
|
+ 由调用方静默跳过注入,绝不阻断方案生成主流程。
|
|
|
+
|
|
|
+ 返回 {"recommend": [...], "avoid": [...], "goal_activation": {...}, "coverage": {...}};
|
|
|
+ 每条食材带 food_name/score/advice_level/sources,供 prompt 溯源与合规口径使用。
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ from app.kb import compute_weighted_foods
|
|
|
+
|
|
|
+ detail = await java.get_report_detail_json(int(report_id))
|
|
|
+ if not detail:
|
|
|
+ return None
|
|
|
+ disease = _extract_disease_related(detail)
|
|
|
+ if not disease:
|
|
|
+ logger.info("报告 %s 详情未含「疾病相关菌」区块,跳过加权食材注入", report_id)
|
|
|
+ return None
|
|
|
+ weighted = compute_weighted_foods({"疾病相关菌": disease})
|
|
|
+ if weighted.get("degraded"):
|
|
|
+ return None
|
|
|
+ recommend = weighted.get("推荐榜") or []
|
|
|
+ avoid = weighted.get("避免榜") or []
|
|
|
+ if not recommend and not avoid:
|
|
|
+ return None
|
|
|
+
|
|
|
+ def _brief(items, limit):
|
|
|
+ return [{
|
|
|
+ "food_name": item.get("food_name"),
|
|
|
+ "score": item.get("score"),
|
|
|
+ "advice_level": item.get("advice_level"),
|
|
|
+ "review_status": item.get("review_status"),
|
|
|
+ "sources": list(item.get("sources") or [])[:3],
|
|
|
+ } for item in items[:limit]]
|
|
|
+
|
|
|
+ return {
|
|
|
+ "recommend": _brief(recommend, top_n),
|
|
|
+ "avoid": _brief(avoid, top_n),
|
|
|
+ "goal_activation": weighted.get("goal_activation") or {},
|
|
|
+ "coverage": weighted.get("coverage") or {},
|
|
|
+ "degraded": False,
|
|
|
+ }
|
|
|
+ except Exception as e:
|
|
|
+ logger.warning("加权食材注入不可用(reportId=%s): %s", report_id, e)
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
+def _format_weighted_foods(weighted: dict | None) -> str:
|
|
|
+ """把成员级加权食材榜渲染进 prompt;advisory 一律不作硬性禁忌。"""
|
|
|
+ if not weighted or weighted.get("degraded"):
|
|
|
+ return ""
|
|
|
+ recommend = weighted.get("recommend") or []
|
|
|
+ avoid = weighted.get("avoid") or []
|
|
|
+ if not recommend and not avoid:
|
|
|
+ return ""
|
|
|
+ lines = ["", "## 个性化食材加权参考(依据该成员菌群检测报告计算,仅供参考,非处方)"]
|
|
|
+ lines.append("以下食材由该成员菌群异常方向加权计算得出,标注 advisory 的仅作提示、"
|
|
|
+ "不作硬性禁忌;使用时须结合个体情况并由专业人员复核。")
|
|
|
+ for label, items, wording in (("优先食材", recommend, "可尝试"),
|
|
|
+ ("减少食材", avoid, "建议减少")):
|
|
|
+ if not items:
|
|
|
+ continue
|
|
|
+ lines.append(f"- {label}({wording}):" + "、".join(
|
|
|
+ str(item.get("food_name")) for item in items if item.get("food_name")))
|
|
|
+ trace = ";".join(
|
|
|
+ f"{item.get('food_name')}(权重{item.get('score'):+.2f},"
|
|
|
+ f"来源{item.get('sources')[:1]},级别{item.get('advice_level')})"
|
|
|
+ for item in items[:3])
|
|
|
+ lines.append(f" 溯源: {trace}")
|
|
|
+ activation = weighted.get("goal_activation") or {}
|
|
|
+ if activation:
|
|
|
+ top = "、".join(f"{goal}({score:.2f})" for goal, score in list(activation.items())[:4])
|
|
|
+ lines.append(f"- 本次加权主要激活的健康目标: {top}")
|
|
|
+ return "\n".join(lines)
|
|
|
+
|
|
|
+
|
|
|
+def _build_kb_structured_context(all_indicators: list, goal: str, dimensions: str) -> dict:
|
|
|
+ """从报告指标/用户目标映射目标,拉取 goal→food 与模板,生成结构化上下文。"""
|
|
|
+ empty = {"goals": [], "templates": [], "degraded": True}
|
|
|
+ try:
|
|
|
+ from app.kb import get_kb_loader
|
|
|
+
|
|
|
+ loader = get_kb_loader()
|
|
|
+ abnormal_names = []
|
|
|
+ for ind in all_indicators[:30]:
|
|
|
+ if not isinstance(ind, dict):
|
|
|
+ continue
|
|
|
+ if ind.get("status") in ("abnormal", "high", "low", "偏高", "偏低"):
|
|
|
+ abnormal_names.append(str(ind.get("indicatorName") or ""))
|
|
|
+ hint_text = " ".join(
|
|
|
+ [str(goal or ""), str(dimensions or "")] + abnormal_names
|
|
|
+ )
|
|
|
+ goal_ids = _kb_goal_ids_from_text(hint_text, loader)
|
|
|
+
|
|
|
+ goals = []
|
|
|
+ modules = set()
|
|
|
+ for goal_id in goal_ids[:3]:
|
|
|
+ rows = loader.get_goal_foods(goal_id)
|
|
|
+ prefer = [r for r in rows if r.get("关系类型") == "推荐"][:8]
|
|
|
+ avoid = [r for r in rows if r.get("关系类型") == "避免"][:8]
|
|
|
+
|
|
|
+ def _brief(items):
|
|
|
+ return [{
|
|
|
+ "name": r.get("food_name"),
|
|
|
+ "source_entry_id": r.get("source_entry_id"),
|
|
|
+ "review_status": r.get("review_status"),
|
|
|
+ "advice_level": r.get("advice_level"),
|
|
|
+ } for r in items]
|
|
|
+
|
|
|
+ goals.append({
|
|
|
+ "goal_id": goal_id,
|
|
|
+ "goal_name": rows[0].get("goal_name") if rows else "",
|
|
|
+ "prefer_foods": _brief(prefer),
|
|
|
+ "avoid_foods": _brief(avoid),
|
|
|
+ })
|
|
|
+ for name, goal_id_value in [(g["goal_name"], g["goal_id"]) for g in loader.list_goals()]:
|
|
|
+ if goal_id_value == goal_id:
|
|
|
+ modules.update(_KB_GOAL_MODULES.get(name, ()))
|
|
|
+
|
|
|
+ templates = []
|
|
|
+ for module in sorted(modules)[:2]:
|
|
|
+ for tpl in loader.get_template(module=module)[:2]:
|
|
|
+ templates.append({
|
|
|
+ "entry_id": tpl.get("entry_id"),
|
|
|
+ "entry_name": tpl.get("entry_name"),
|
|
|
+ "module": tpl.get("module"),
|
|
|
+ "status": tpl.get("status"),
|
|
|
+ "skeleton": str(tpl.get("skeleton") or "")[:160],
|
|
|
+ "source_entry_id": tpl.get("source_entry_id"),
|
|
|
+ "review_status": tpl.get("review_status"),
|
|
|
+ "advice_level": tpl.get("advice_level"),
|
|
|
+ })
|
|
|
+ return {"goals": goals, "templates": templates[:6], "degraded": False}
|
|
|
+ except Exception as e:
|
|
|
+ logger.warning("结构化知识库上下文不可用,忽略: %s", e)
|
|
|
+ return empty
|
|
|
+
|
|
|
+
|
|
|
+def _format_kb_structured_context(context: dict | None) -> str:
|
|
|
+ """把结构化上下文写入 prompt;pending-review 仅提示、advisory 不作硬性禁忌。"""
|
|
|
+ if not context or context.get("degraded"):
|
|
|
+ return ""
|
|
|
+ goals = context.get("goals") or []
|
|
|
+ templates = context.get("templates") or []
|
|
|
+ if not goals and not templates:
|
|
|
+ return ""
|
|
|
+ lines = [
|
|
|
+ "",
|
|
|
+ "## 结构化知识库参考(仅供参考,非处方)",
|
|
|
+ "以下为结构化知识库参考,标注 pending-review 的条目仅作提示、不作处方,"
|
|
|
+ "advisory 不作硬性禁忌;使用时须结合个体情况并由专业人员复核。",
|
|
|
+ ]
|
|
|
+ for goal in goals:
|
|
|
+ lines.append(f"- 目标[{goal.get('goal_id')}] {goal.get('goal_name') or ''}:")
|
|
|
+ for label, key, wording in (
|
|
|
+ ("优先食材(推荐)", "prefer_foods", "可尝试"),
|
|
|
+ ("注意食材(避免)", "avoid_foods", "建议减少"),
|
|
|
+ ):
|
|
|
+ items = goal.get(key) or []
|
|
|
+ if not items:
|
|
|
+ continue
|
|
|
+ names = "、".join(str(item.get("name")) for item in items if item.get("name"))
|
|
|
+ trace = ";".join(
|
|
|
+ f"{item.get('name')}[来源:{item.get('source_entry_id')}, "
|
|
|
+ f"复核:{item.get('review_status')}, 级别:{item.get('advice_level')}]"
|
|
|
+ for item in items[:3]
|
|
|
+ )
|
|
|
+ lines.append(f" - {label}: {wording} {names}")
|
|
|
+ lines.append(f" 追溯: {trace}")
|
|
|
+ for tpl in templates:
|
|
|
+ lines.append(
|
|
|
+ f"- 模板[{tpl.get('entry_id')}] {tpl.get('entry_name')} "
|
|
|
+ f"(module={tpl.get('module')}, status={tpl.get('status')}, "
|
|
|
+ f"来源:{tpl.get('source_entry_id')}, 复核:{tpl.get('review_status')}, "
|
|
|
+ f"级别:{tpl.get('advice_level')}): {tpl.get('skeleton')}"
|
|
|
+ )
|
|
|
+ return "\n".join(lines)
|
|
|
+
|
|
|
+
|
|
|
async def _collect_plan_data(java: JavaClient, retriever: RagRetriever, member_ids_str: str, goal: str, dimensions: str):
|
|
|
"""统一数据收集逻辑"""
|
|
|
member_ids = [m.strip() for m in member_ids_str.split(",") if m.strip()]
|
|
|
@@ -905,6 +1149,11 @@ async def _collect_plan_data(java: JavaClient, retriever: RagRetriever, member_i
|
|
|
for ind in indicators:
|
|
|
ind["_member_name"] = member["name"]
|
|
|
all_indicators.append(ind)
|
|
|
+ # 个性化食材加权榜(规范 §四):仅菌群报告成员;后端未补「疾病相关菌」时安全降级。
|
|
|
+ if member.get("has_gut_flora"):
|
|
|
+ weighted = await _member_weighted_foods(java, latest.get("id"))
|
|
|
+ if weighted:
|
|
|
+ member["weighted_foods"] = weighted
|
|
|
|
|
|
# 2.5 健康自检问卷(health_status;未填写为空 dict)
|
|
|
for member in members_info:
|
|
|
@@ -930,7 +1179,10 @@ async def _collect_plan_data(java: JavaClient, retriever: RagRetriever, member_i
|
|
|
results = await retriever.retrieve(q, k=3)
|
|
|
kb_results.extend(results)
|
|
|
|
|
|
- return members_info, all_indicators, kb_results
|
|
|
+ # 结构化知识库补充:与主 RAG 检索独立,失败时返回 degraded=True 由 prompt 侧忽略。
|
|
|
+ kb_structured_context = _build_kb_structured_context(all_indicators, goal, dimensions)
|
|
|
+
|
|
|
+ return members_info, all_indicators, kb_results, kb_structured_context
|
|
|
|
|
|
|
|
|
def _detect_follow_up_questions(members_info: list, follow_up_answers: Optional[dict]) -> list:
|
|
|
@@ -1144,7 +1396,8 @@ MULTI_MEMBER_SYNTHESIS_PROMPT = """你是一个家庭健康方案规划师。以
|
|
|
- 若某 section 没有可执行的行动项,`tasks` 输出空数组 `[]`。"""
|
|
|
|
|
|
|
|
|
-def _build_individual_plan_prompt(member: dict, member_indicators: list, kb_results: list, goal: str, dimensions: str) -> str:
|
|
|
+def _build_individual_plan_prompt(member: dict, member_indicators: list, kb_results: list, goal: str, dimensions: str,
|
|
|
+ kb_structured_context: dict | None = None) -> str:
|
|
|
"""为单个成员构建独立方案生成 prompt(只含该成员自身数据)。"""
|
|
|
parts = [PLAN_SYSTEM_PROMPT]
|
|
|
parts.append(f"\n## 用户目标\n{goal}")
|
|
|
@@ -1184,12 +1437,20 @@ def _build_individual_plan_prompt(member: dict, member_indicators: list, kb_resu
|
|
|
title = r.get("metadata", {}).get("title", "")
|
|
|
content = r.get("content", "")[:200]
|
|
|
parts.append(f"---\n{title}\n{content}")
|
|
|
+ kb_context_text = _format_kb_structured_context(kb_structured_context)
|
|
|
+ if kb_context_text:
|
|
|
+ parts.append(kb_context_text)
|
|
|
+ # 成员级个性化食材加权榜(依据该成员菌群报告;无数据则整段省略)
|
|
|
+ weighted_text = _format_weighted_foods(member.get("weighted_foods"))
|
|
|
+ if weighted_text:
|
|
|
+ parts.append(weighted_text)
|
|
|
return "\n".join(parts)
|
|
|
|
|
|
|
|
|
-async def _generate_individual_plan(llm, member: dict, member_indicators: list, kb_results: list, goal: str, dimensions: str) -> dict:
|
|
|
+async def _generate_individual_plan(llm, member: dict, member_indicators: list, kb_results: list, goal: str, dimensions: str,
|
|
|
+ kb_structured_context: dict | None = None) -> dict:
|
|
|
"""为单个成员调用 LLM 生成独立方案;返回 HealthPlanResponse.model_dump() 结构,失败返回 {}。"""
|
|
|
- prompt = _build_individual_plan_prompt(member, member_indicators, kb_results, goal, dimensions)
|
|
|
+ prompt = _build_individual_plan_prompt(member, member_indicators, kb_results, goal, dimensions, kb_structured_context)
|
|
|
try:
|
|
|
response = await llm.ainvoke([SystemMessage(content=prompt)])
|
|
|
result = _parse_plan_response(response.content)
|
|
|
@@ -1288,7 +1549,7 @@ async def health_plan_generate(req: HealthPlanRequest):
|
|
|
temperature=0.3,
|
|
|
)
|
|
|
|
|
|
- members_info, all_indicators, kb_results = await _collect_plan_data(java, retriever, req.member_ids or "", goal, req.dimensions or "")
|
|
|
+ members_info, all_indicators, kb_results, kb_structured_context = await _collect_plan_data(java, retriever, req.member_ids or "", goal, req.dimensions or "")
|
|
|
|
|
|
# 获取每个成员的画像数据
|
|
|
for member in members_info:
|
|
|
@@ -1306,7 +1567,7 @@ async def health_plan_generate(req: HealthPlanRequest):
|
|
|
individual_plans = {}
|
|
|
for member in members_info:
|
|
|
member_indicators = [ind for ind in all_indicators if ind.get("_member_name") == member["name"]]
|
|
|
- plan = await _generate_individual_plan(llm, member, member_indicators, kb_results, goal, req.dimensions or "")
|
|
|
+ plan = await _generate_individual_plan(llm, member, member_indicators, kb_results, goal, req.dimensions or "", kb_structured_context)
|
|
|
individual_plans[str(member["id"])] = plan
|
|
|
result = await _synthesize_multi_member_plan(llm, members_info, individual_plans, goal, req.dimensions or "",
|
|
|
follow_up_answers=req.follow_up_answers)
|
|
|
@@ -1356,6 +1617,9 @@ async def health_plan_generate(req: HealthPlanRequest):
|
|
|
title = r.get("metadata", {}).get("title", "")
|
|
|
content = r.get("content", "")[:200]
|
|
|
parts.append(f"---\n{title}\n{content}")
|
|
|
+ kb_context_text = _format_kb_structured_context(kb_structured_context)
|
|
|
+ if kb_context_text:
|
|
|
+ parts.append(kb_context_text)
|
|
|
|
|
|
full_prompt = "\n".join(parts)
|
|
|
# HL-03/R3:用户补充回答并入单人生成 prompt(首次为空串)
|
|
|
@@ -1386,7 +1650,7 @@ async def health_plan_regenerate(req: HealthPlanRegenerateRequest):
|
|
|
temperature=0.3,
|
|
|
)
|
|
|
|
|
|
- members_info, all_indicators, kb_results = await _collect_plan_data(java, None, req.member_ids or "", req.goal, req.dimensions or "")
|
|
|
+ members_info, all_indicators, kb_results, _ = await _collect_plan_data(java, None, req.member_ids or "", req.goal, req.dimensions or "")
|
|
|
|
|
|
# 构建上下文
|
|
|
ctx_parts = [f"目标: {req.goal}"]
|
|
|
@@ -1447,7 +1711,7 @@ async def health_plan_adjust(req: HealthPlanAdjustRequest):
|
|
|
temperature=0.3,
|
|
|
)
|
|
|
|
|
|
- members_info, all_indicators, kb_results = await _collect_plan_data(java, None, req.member_ids or "", req.goal, req.dimensions or "")
|
|
|
+ members_info, all_indicators, kb_results, _ = await _collect_plan_data(java, None, req.member_ids or "", req.goal, req.dimensions or "")
|
|
|
|
|
|
# 构建上下文
|
|
|
ctx_parts = [f"目标: {req.goal}"]
|