adapter.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. from fastapi import APIRouter, HTTPException
  2. from pydantic import BaseModel, ConfigDict
  3. from typing import Optional
  4. from app.graphs.chat_graph import create_chat_graph
  5. from app.graphs.analysis_graph import create_analysis_graph
  6. from app.graphs.health_coach_graph import create_health_coach_graph
  7. from app.graphs.health_butler_graph import create_health_butler_graph
  8. from app.tools.java_client import JavaClient
  9. from app.rag.retriever import RagRetriever
  10. from app.config import settings
  11. from langchain_openai import ChatOpenAI
  12. from langchain_core.messages import SystemMessage, HumanMessage
  13. import uuid
  14. import time
  15. import re
  16. import logging
  17. import json
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/api/v1", tags=["adapter"])
  20. # ---- Dify-compatible request/response models ----
  21. class DifyMessage(BaseModel):
  22. role: str
  23. content: str
  24. class DifyChatRequest(BaseModel):
  25. # 前端 userId/conversationId 可能为数字,允许 int/float 自动转 str,避免 422
  26. model_config = ConfigDict(coerce_numbers_to_str=True)
  27. query: str = ""
  28. user: str = "anonymous"
  29. conversation_id: str = ""
  30. messages: list[DifyMessage] = []
  31. inputs: dict = {}
  32. response_mode: str = "blocking" # blocking / streaming
  33. user_id: str = ""
  34. bot_name: str = "AI管家"
  35. class DifyAnalysisRequest(BaseModel):
  36. # 前端 userId 可能为数字,允许 int/float 自动转 str,避免 422
  37. model_config = ConfigDict(coerce_numbers_to_str=True)
  38. report_id: Optional[int] = None
  39. user_id: Optional[str] = None
  40. focus: Optional[str] = None
  41. messages: list[DifyMessage] = []
  42. inputs: dict = {}
  43. class HealthCoachGenerateRequest(BaseModel):
  44. """Java 后端健康方案生成专用请求体"""
  45. family_id: Optional[int] = None
  46. member_ids: Optional[str] = None
  47. dimensions: Optional[str] = None
  48. goal: str = ""
  49. class DifyChoice(BaseModel):
  50. index: int
  51. message: dict
  52. finish_reason: str = "stop"
  53. class DifyUsage(BaseModel):
  54. prompt_tokens: int = 0
  55. completion_tokens: int = 0
  56. total_tokens: int = 0
  57. class DifyResponse(BaseModel):
  58. id: str
  59. object: str = "chat.completion"
  60. created: int
  61. model: str = "langgraph-cfc"
  62. choices: list[DifyChoice]
  63. usage: DifyUsage = DifyUsage()
  64. metadata: dict = {}
  65. # ---- Helpers ----
  66. def _now_ts() -> int:
  67. return int(time.time())
  68. def _extract_query(req: DifyChatRequest) -> str:
  69. if req.query:
  70. return req.query
  71. # fallback: take last user message
  72. for msg in reversed(req.messages):
  73. if msg.role == "user":
  74. return msg.content
  75. return ""
  76. def _to_langgraph_context(req: DifyChatRequest) -> dict:
  77. ctx = {}
  78. if isinstance(req.inputs, dict):
  79. ctx["child_id"] = req.inputs.get("child_id")
  80. ctx["report_id"] = req.inputs.get("report_id")
  81. ctx["family_id"] = req.inputs.get("family_id")
  82. return ctx
  83. # ---- Dify-compatible endpoints ----
  84. @router.post("/chat/completion", response_model=DifyResponse)
  85. async def chat_completion(req: DifyChatRequest):
  86. query = _extract_query(req)
  87. if not query:
  88. raise HTTPException(status_code=400, detail="query 为空")
  89. graph = create_chat_graph()
  90. initial_state = {
  91. "query": query,
  92. "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
  93. "conversation_id": req.conversation_id or None,
  94. "intent": None,
  95. "context": _to_langgraph_context(req),
  96. "messages": None,
  97. "answer": None,
  98. "tasks": [],
  99. "sources": [],
  100. }
  101. config = {
  102. "configurable": {"thread_id": req.conversation_id or str(req.user_id or "default")},
  103. }
  104. result = await graph.ainvoke(initial_state, config)
  105. answer = result.get("answer") or ""
  106. return DifyResponse(
  107. id=f"chatcmpl-{uuid.uuid4().hex[:24]}",
  108. created=_now_ts(),
  109. choices=[
  110. DifyChoice(
  111. index=0,
  112. message={"role": "assistant", "content": answer},
  113. finish_reason="stop",
  114. )
  115. ],
  116. usage=DifyUsage(
  117. prompt_tokens=len(query.split()),
  118. completion_tokens=len(answer.split()),
  119. total_tokens=len(query.split()) + len(answer.split()),
  120. ),
  121. )
  122. @router.post("/analysis/run", response_model=DifyResponse)
  123. async def analysis_run(req: DifyAnalysisRequest):
  124. graph = create_analysis_graph()
  125. report_id = req.report_id
  126. if report_id is None and isinstance(req.inputs, dict):
  127. report_id = req.inputs.get("report_id")
  128. initial_state = {
  129. "report_id": report_id,
  130. "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
  131. "focus": req.focus,
  132. "report_data": None,
  133. "survey_data": None,
  134. "dimension_scores": None,
  135. "analysis": None,
  136. "recommendations": [],
  137. }
  138. result = await graph.ainvoke(initial_state, {})
  139. analysis = result.get("analysis") or ""
  140. recommendations = result.get("recommendations") or []
  141. content = analysis
  142. if recommendations:
  143. content += "\n\n建议:\n" + "\n".join(f"- {r}" for r in recommendations)
  144. return DifyResponse(
  145. id=f"analysis-{uuid.uuid4().hex[:24]}",
  146. created=_now_ts(),
  147. choices=[
  148. DifyChoice(
  149. index=0,
  150. message={"role": "assistant", "content": content},
  151. finish_reason="stop",
  152. )
  153. ],
  154. usage=DifyUsage(
  155. prompt_tokens=len((req.focus or "").split()),
  156. completion_tokens=len(content.split()),
  157. total_tokens=len((req.focus or "").split()) + len(content.split()),
  158. ),
  159. )
  160. @router.post("/health/coach", response_model=DifyResponse)
  161. async def health_coach(req: DifyChatRequest):
  162. query = _extract_query(req)
  163. if not query:
  164. raise HTTPException(status_code=400, detail="query 为空")
  165. graph = create_health_coach_graph()
  166. initial_state = {
  167. "query": query,
  168. "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
  169. "child_id": int(req.inputs.get("child_id")) if req.inputs.get("child_id") else None,
  170. "conversation_id": req.conversation_id or None,
  171. "context": _to_langgraph_context(req),
  172. "answer": None,
  173. "sources": [],
  174. "memory_messages": None,
  175. }
  176. config = {
  177. "configurable": {"thread_id": req.conversation_id or f"health_{req.user_id}"},
  178. }
  179. result = await graph.ainvoke(initial_state, config)
  180. answer = result.get("answer") or ""
  181. sources = result.get("sources") or []
  182. metadata = {}
  183. if sources:
  184. metadata["sources"] = [
  185. {"title": s.get("title", ""), "type": s.get("type", "knowledge")}
  186. for s in sources
  187. ]
  188. return DifyResponse(
  189. id=f"health-{uuid.uuid4().hex[:24]}",
  190. created=_now_ts(),
  191. model="langgraph-health-coach",
  192. choices=[
  193. DifyChoice(
  194. index=0,
  195. message={"role": "assistant", "content": answer},
  196. finish_reason="stop",
  197. )
  198. ],
  199. usage=DifyUsage(
  200. prompt_tokens=len(query.split()),
  201. completion_tokens=len(answer.split()),
  202. total_tokens=len(query.split()) + len(answer.split()),
  203. ),
  204. metadata=metadata,
  205. )
  206. @router.post("/health/butler", response_model=DifyResponse)
  207. async def health_butler(req: DifyChatRequest):
  208. """AI 健康管家 — 基于健康知识库检索 + 个性化建议 + 任务生成"""
  209. query = _extract_query(req)
  210. if not query:
  211. raise HTTPException(status_code=400, detail="query 为空")
  212. graph = create_health_butler_graph()
  213. # 从 inputs 中提取健康管家需要的上下文
  214. inputs = req.inputs or {}
  215. family_id = inputs.get("family_id")
  216. child_id = inputs.get("child_id")
  217. report_id = inputs.get("report_id")
  218. focus = inputs.get("focus")
  219. # conversation_id 用于 checkpointer thread
  220. thread_id = req.conversation_id or f"butler_{req.user_id or 'anon'}"
  221. initial_state = {
  222. "query": query,
  223. "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
  224. "conversation_id": thread_id,
  225. "family_id": int(family_id) if family_id else None,
  226. "child_id": int(child_id) if child_id else None,
  227. "report_id": int(report_id) if report_id else None,
  228. "focus": focus,
  229. "kb_context": None,
  230. "knowledge_results": [],
  231. "answer": None,
  232. "tasks": [],
  233. "sources": [],
  234. "messages": None,
  235. }
  236. config = {
  237. "configurable": {"thread_id": thread_id},
  238. }
  239. result = await graph.ainvoke(initial_state, config)
  240. answer = result.get("answer") or ""
  241. # 从回答中提取 TASK 标记
  242. tasks = result.get("tasks") or []
  243. sources = result.get("sources") or []
  244. metadata = {"tasks": tasks, "sources": sources}
  245. return DifyResponse(
  246. id=f"butler-{uuid.uuid4().hex[:24]}",
  247. created=_now_ts(),
  248. model="langgraph-health-butler",
  249. choices=[
  250. DifyChoice(
  251. index=0,
  252. message={"role": "assistant", "content": answer},
  253. finish_reason="stop",
  254. )
  255. ],
  256. usage=DifyUsage(
  257. prompt_tokens=len(query.split()),
  258. completion_tokens=len(answer.split()),
  259. total_tokens=len(query.split()) + len(answer.split()),
  260. ),
  261. metadata=metadata,
  262. )
  263. def _parse_normal_range(ref_range: str) -> tuple[float | None, float | None]:
  264. """解析正常范围字符串,返回 (下限, 上限),如 '30-100' → (30, 100), '<5' → (None, 5)"""
  265. if not ref_range:
  266. return None, None
  267. ref_range = ref_range.strip()
  268. m = re.match(r'([<>]=?)\s*([\d.]+)', ref_range)
  269. if m:
  270. op, val = m.group(1), float(m.group(2))
  271. if op.startswith('>'):
  272. return (val, None)
  273. else:
  274. return (None, val)
  275. m = re.match(r'([\d.]+)\s*[-~]\s*([\d.]+)', ref_range)
  276. if m:
  277. return (float(m.group(1)), float(m.group(2)))
  278. return None, None
  279. def _is_abnormal(status: str, value: float | None, low: float | None, high: float | None) -> bool:
  280. """判断指标是否异常:优先用 status 字段,否则用数值与范围比较"""
  281. if status and status not in ("正常", "正常范围", "未检出", ""):
  282. return True
  283. if value is not None and low is not None and high is not None:
  284. return value < low or value > high
  285. return False
  286. def _try_parse_value(raw: str) -> float | None:
  287. if not raw:
  288. return None
  289. raw = raw.strip().replace(",", "").replace(" ", "")
  290. try:
  291. return float(raw)
  292. except ValueError:
  293. return None
  294. async def _search_knowledge(retriever: RagRetriever, query: str, k: int = 3) -> list[dict]:
  295. """从知识库检索相关内容"""
  296. try:
  297. return await retriever.retrieve(query, k=k)
  298. except Exception as e:
  299. logger.warning("知识库检索失败: %s", e)
  300. return []
  301. @router.post("/health/coach/generate")
  302. async def health_coach_generate(req: HealthCoachGenerateRequest):
  303. """健康方案生成 — 选人→拉指标→查知识库→LLM"""
  304. goal = req.goal or "改善健康状况"
  305. member_ids_str = req.member_ids or ""
  306. dimensions = req.dimensions or ""
  307. member_ids = [m.strip() for m in member_ids_str.split(",") if m.strip()]
  308. java = JavaClient()
  309. retriever = RagRetriever(collection_name="cfc_knowledge")
  310. llm = ChatOpenAI(
  311. model=settings.llm_model,
  312. api_key=settings.llm_api_key,
  313. base_url=settings.llm_base_url,
  314. temperature=0.3,
  315. )
  316. # ====== 1. 获取家庭成员信息 ======
  317. members_info = []
  318. if member_ids:
  319. # 从 context 获取家庭信息
  320. for uid_str in member_ids:
  321. uid = int(uid_str)
  322. ctx = await java.get_family_context(uid, "child_info")
  323. children = ctx.get("children", []) if isinstance(ctx, dict) else []
  324. for child in children:
  325. child_id = str(child.get("用户ID", ""))
  326. if child_id in member_ids:
  327. members_info.append({
  328. "id": child_id,
  329. "name": child.get("姓名", f"成员{child_id}"),
  330. "age": child.get("年龄", "未知"),
  331. "energy": child.get("能量", 0),
  332. })
  333. break
  334. # 如果 context 没找到,用基本信息兜底
  335. if not any(m["id"] == uid_str for m in members_info):
  336. members_info.append({"id": uid_str, "name": f"成员{uid_str}", "age": "未知", "energy": 0})
  337. else:
  338. members_info.append({"id": "0", "name": "用户", "age": "未知", "energy": 0})
  339. # ====== 2. 获取每个成员的指标数据 ======
  340. all_indicators = []
  341. for member in members_info:
  342. uid = int(member["id"])
  343. reports = await java.get_member_reports(uid)
  344. if not reports:
  345. logger.info("成员 %s 无健康报告", member["id"])
  346. continue
  347. latest = max(reports, key=lambda r: r.get("reportDate", ""))
  348. report_id = latest.get("id")
  349. member["latest_report_id"] = report_id
  350. member["report_date"] = latest.get("reportDate", "")
  351. member["overall_score"] = latest.get("overallScore", "未知")
  352. indicators = await java.get_report_indicators(report_id)
  353. for ind in indicators:
  354. ind["_member_id"] = member["id"]
  355. ind["_member_name"] = member["name"]
  356. all_indicators.append(ind)
  357. # ====== 3. 获取指标定义+正常范围 ======
  358. known_indicators = {}
  359. for ind in all_indicators:
  360. name = ind.get("indicatorName", "").strip()
  361. if not name or name in known_indicators:
  362. continue
  363. kb = await java.query_health_knowledge("indicator", name)
  364. if not kb:
  365. kb = await java.query_health_knowledge("bacteria", name)
  366. if not kb:
  367. kb = await java.query_health_knowledge("nutrient", name)
  368. if kb:
  369. known_indicators[name] = kb
  370. # ====== 4. 识别异常指标 ======
  371. abnormal_list = []
  372. normal_list = []
  373. for ind in all_indicators:
  374. name = ind.get("indicatorName", "")
  375. raw_val = ind.get("indicatorValue", "")
  376. status = ind.get("status", "")
  377. unit = ind.get("unit", "")
  378. ref_range = ind.get("refRange", "")
  379. # 优先用知识库中的正常范围
  380. kb = known_indicators.get(name)
  381. if kb and kb.get("normalRange"):
  382. ref_range = kb.get("normalRange", ref_range)
  383. low, high = _parse_normal_range(ref_range)
  384. value = _try_parse_value(raw_val)
  385. is_abnormal = _is_abnormal(status, value, low, high)
  386. entry = {
  387. "member": ind.get("_member_name", ""),
  388. "indicator": name,
  389. "value": raw_val,
  390. "unit": unit,
  391. "ref_range": ref_range,
  392. "status": status,
  393. "is_abnormal": is_abnormal,
  394. "description": kb.get("description", "") if kb else "",
  395. "suggestion": kb.get("suggestion", "") if kb else "",
  396. }
  397. if is_abnormal:
  398. abnormal_list.append(entry)
  399. else:
  400. normal_list.append(entry)
  401. # ====== 5. 检索知识库 ======
  402. kb_results = []
  403. # 5a. 异常指标检索
  404. abnormal_queries = set()
  405. for ind in abnormal_list:
  406. abnormal_queries.add(ind["indicator"])
  407. for q in list(abnormal_queries)[:5]:
  408. results = await _search_knowledge(retriever, f"{q} 改善建议", k=3)
  409. kb_results.extend(results)
  410. # 5b. 用户需求检索
  411. goal_results = await _search_knowledge(retriever, goal, k=5)
  412. kb_results.extend(goal_results)
  413. # 5c. 维度检索
  414. if dimensions:
  415. dim_results = await _search_knowledge(retriever, dimensions, k=3)
  416. kb_results.extend(dim_results)
  417. # 去重
  418. seen_content = set()
  419. deduped_kb = []
  420. for r in kb_results:
  421. h = r.get("content", "")[:100]
  422. if h not in seen_content:
  423. seen_content.add(h)
  424. deduped_kb.append(r)
  425. # ====== 6. 组装结构化 Prompt ======
  426. prompt_parts = []
  427. # 系统提示
  428. prompt_parts.append("""你是一个专业的家庭健康方案生成器。请根据用户提供的健康数据,生成一份结构化的健康改善方案。
  429. 输出格式要求:
  430. ## 方案概述
  431. [简要说明方案的总体目标和适用对象]
  432. ## 成员健康概况
  433. [每个成员的关键指标摘要]
  434. ## 需要关注的异常指标
  435. [列出异常指标及对应的知识库建议]
  436. ## 改善方案
  437. ### 1. 饮食调整
  438. [具体、可执行的饮食建议]
  439. ### 2. 生活习惯
  440. [具体、可执行的生活习惯建议]
  441. ### 3. 补充建议
  442. [如需补充营养素或益生菌,给出具体建议]
  443. ### 4. 跟踪建议
  444. [建议定期复查的指标和频率]
  445. ## 注意事项
  446. [禁忌、提醒等]
  447. 请基于实际数据给出建议,不要编造科学依据。引用知识库内容时标注来源。""")
  448. # 目标与维度
  449. prompt_parts.append(f"\n## 用户目标\n{goal}")
  450. if dimensions:
  451. prompt_parts.append(f"\n## 重点关注维度\n{dimensions}")
  452. # 成员信息
  453. prompt_parts.append("\n## 家庭成员")
  454. for m in members_info:
  455. scores = f"健康评分: {m.get('overall_score', '未知')}" if m.get('overall_score') else ""
  456. report = f"最近报告: {m.get('report_date', '无')}" if m.get('report_date') else ""
  457. prompt_parts.append(f"- {m['name']} (年龄: {m['age']}) {scores} {report}")
  458. # 异常指标
  459. if abnormal_list:
  460. prompt_parts.append("\n## 异常指标")
  461. for ind in abnormal_list:
  462. parts = [f"- {ind['member']} - {ind['indicator']}: {ind['value']}{ind['unit']} (参考范围: {ind['ref_range']})"]
  463. if ind['description']:
  464. parts.append(f" 说明: {ind['description']}")
  465. if ind['suggestion']:
  466. parts.append(f" 建议: {ind['suggestion']}")
  467. prompt_parts.append("\n".join(parts))
  468. # 正常指标
  469. if normal_list:
  470. prompt_parts.append("\n## 正常指标(参考)")
  471. normal_summary = [f"- {ind['indicator']}: {ind['value']}{ind['unit']} (正常)" for ind in normal_list[:10]]
  472. prompt_parts.extend(normal_summary)
  473. # 知识库参考
  474. if deduped_kb:
  475. prompt_parts.append("\n## 知识库参考(可引用)")
  476. for r in deduped_kb[:8]:
  477. title = r.get("metadata", {}).get("title", "")
  478. content = r.get("content", "")[:300]
  479. prompt_parts.append(f"---\n{title}\n{content}")
  480. full_prompt = "\n".join(prompt_parts)
  481. # ====== 7. 调用 LLM ======
  482. messages = [
  483. SystemMessage(content=full_prompt),
  484. HumanMessage(content=f"请基于以上数据,生成一份针对{goal}的健康改善方案。"),
  485. ]
  486. response = await llm.ainvoke(messages)
  487. answer = response.content
  488. return answer
  489. # ===== 健康方案生成(结构化 JSON)=====
  490. class HealthPlanRequest(BaseModel):
  491. member_ids: Optional[str] = None
  492. dimensions: Optional[str] = None
  493. goal: str = ""
  494. family_id: Optional[int] = None
  495. class HealthPlanRegenerateRequest(BaseModel):
  496. section: str # nutrition | diet | exercise
  497. feedback: str = ""
  498. existing_section_content: str = ""
  499. member_ids: Optional[str] = None
  500. dimensions: Optional[str] = None
  501. goal: str = ""
  502. family_id: Optional[int] = None
  503. PLAN_SYSTEM_PROMPT = """你是一个专业的家庭健康方案规划师。根据用户提供的健康数据和目标,生成结构化的健康改善方案。
  504. ## 输出格式(必须输出合法 JSON,不要有其他内容)
  505. {
  506. "overview": "总体概述(100字以内,说明方案目标和核心策略)",
  507. "sections": [
  508. {
  509. "key": "nutrition",
  510. "title": "营养补充建议",
  511. "content": "Markdown 格式的详细内容",
  512. "items": [
  513. {"name": "产品名", "dosage": "用量", "timing": "服用时间", "reason": "推荐理由"}
  514. ]
  515. },
  516. {
  517. "key": "diet",
  518. "title": "饮食建议",
  519. "content": "Markdown 格式的餐饮建议",
  520. "items": [{"meal": "餐型", "food": "食物建议", "notes": "注意事项"}]
  521. },
  522. {
  523. "key": "exercise",
  524. "title": "运动计划",
  525. "content": "Markdown 格式的运动建议",
  526. "items": [{"type": "运动类型", "duration": "时长", "frequency": "频率", "notes": "注意事项"}]
  527. }
  528. ],
  529. "abnormal_indicators": [
  530. {"member": "姓名", "indicator": "指标名", "value": "值", "unit": "单位", "suggestion": "建议"}
  531. ]
  532. }
  533. ## 原则
  534. 1. 基于实际数据给出建议,不编造
  535. 2. 引用知识库内容时标注来源
  536. 3. 建议要具体可执行,避免空泛
  537. 4. 营养补充部分要具体到产品类型和用量
  538. 5. 严重健康问题建议咨询医生
  539. ## 画像数据使用指南
  540. 如果提供了用户的画像数据(五维评分、身体指标、心理指标等),请结合这些真实数据给出更有针对性的建议。特别关注异常指标(如睡眠不足、压力偏高、运动频率低等),在方案中明确说明这些指标的现状和改善方向。
  541. """
  542. REGENERATE_SECTION_SYSTEM_PROMPT = """你是一个家庭健康方案规划师。根据用户反馈重新生成指定部分内容。
  543. ## 输出格式
  544. 只输出新的 content 字段值(Markdown 格式字符串),不要输出 JSON 结构。
  545. ## 原则
  546. - 保持与原格式一致
  547. - 结合用户反馈进行修改
  548. - 建议要具体可执行"""
  549. async def _collect_plan_data(java: JavaClient, retriever: RagRetriever, member_ids_str: str, goal: str, dimensions: str):
  550. """统一数据收集逻辑"""
  551. member_ids = [m.strip() for m in member_ids_str.split(",") if m.strip()]
  552. # 1. 家庭成员信息
  553. members_info = []
  554. for uid_str in member_ids:
  555. ctx = await java.get_family_context(int(uid_str), "child_info")
  556. children = ctx.get("children", []) if isinstance(ctx, dict) else []
  557. for child in children:
  558. cid = str(child.get("用户ID", ""))
  559. if cid == uid_str:
  560. members_info.append({
  561. "id": cid,
  562. "name": child.get("姓名", f"成员{cid}"),
  563. "age": child.get("年龄", "未知"),
  564. })
  565. break
  566. if not any(m["id"] == uid_str for m in members_info):
  567. members_info.append({"id": uid_str, "name": f"成员{uid_str}", "age": "未知"})
  568. # 2. 健康指标
  569. all_indicators = []
  570. abnormal_list = []
  571. for member in members_info:
  572. reports = await java.get_member_reports(int(member["id"]))
  573. if not reports:
  574. continue
  575. latest = max(reports, key=lambda r: r.get("reportDate", ""))
  576. indicators = await java.get_report_indicators(latest.get("id"))
  577. for ind in indicators:
  578. ind["_member_name"] = member["name"]
  579. all_indicators.append(ind)
  580. # 3. 知识库
  581. kb_results = []
  582. queries = set()
  583. for ind in all_indicators:
  584. queries.add(ind.get("indicatorName", ""))
  585. queries.add(goal)
  586. if dimensions:
  587. queries.add(dimensions)
  588. for q in list(queries)[:8]:
  589. if q:
  590. results = await retriever.retrieve(q, k=3)
  591. kb_results.extend(results)
  592. return members_info, all_indicators, kb_results
  593. @router.post("/health/plan/generate", response_model=dict)
  594. async def health_plan_generate(req: HealthPlanRequest):
  595. """健康方案生成 — 返回结构化 JSON(总览+营养+饮食+运动)"""
  596. goal = req.goal or "改善健康状况"
  597. java = JavaClient()
  598. retriever = RagRetriever(collection_name="cfc_knowledge")
  599. llm = ChatOpenAI(
  600. model=settings.llm_model,
  601. api_key=settings.llm_api_key,
  602. base_url=settings.llm_base_url,
  603. temperature=0.3,
  604. )
  605. members_info, all_indicators, kb_results = await _collect_plan_data(java, retriever, req.member_ids or "", goal, req.dimensions or "")
  606. # 获取每个成员的画像数据
  607. for member in members_info:
  608. try:
  609. profile = await java.get_member_profile(int(member["id"]))
  610. member["profile"] = profile
  611. except Exception:
  612. member["profile"] = {}
  613. # 构建 prompt
  614. parts = [PLAN_SYSTEM_PROMPT]
  615. parts.append(f"\n## 用户目标\n{goal}")
  616. if req.dimensions:
  617. parts.append(f"\n## 重点关注维度\n{req.dimensions}")
  618. parts.append("\n## 家庭成员")
  619. for m in members_info:
  620. profile = m.get("profile", {})
  621. dims = profile.get("dimension_scores", {})
  622. body = profile.get("body_metrics", {})
  623. mind = profile.get("mind_metrics", {})
  624. parts.append(f"- {m['name']} (年龄: {m['age']})")
  625. if dims:
  626. parts.append(f" 五维评分: 身{dims.get('body','?')} 智{dims.get('wisdom','?')} 心{dims.get('mind','?')} 行{dims.get('action','?')} 富{dims.get('wealth','?')}")
  627. if body.get('sleep_dur_avg'):
  628. parts.append(f" 平均睡眠: {body['sleep_dur_avg']}小时/天")
  629. if mind.get('stress_avg'):
  630. parts.append(f" 平均压力: {mind['stress_avg']}/10")
  631. if body.get('exercise_count_week'):
  632. parts.append(f" 周运动: {body['exercise_count_week']}次")
  633. if all_indicators:
  634. parts.append("\n## 健康指标摘要")
  635. for ind in all_indicators[:15]:
  636. status = ind.get("status", "")
  637. if status in ("abnormal", "high", "low", "偏高", "偏低"):
  638. parts.append(f"- 【异常】{ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')} (状态: {status})")
  639. else:
  640. parts.append(f"- {ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')}")
  641. if kb_results:
  642. parts.append("\n## 知识库参考")
  643. for r in kb_results[:6]:
  644. title = r.get("metadata", {}).get("title", "")
  645. content = r.get("content", "")[:200]
  646. parts.append(f"---\n{title}\n{content}")
  647. full_prompt = "\n".join(parts)
  648. messages = [SystemMessage(content=full_prompt)]
  649. try:
  650. response = await llm.ainvoke(messages)
  651. answer = response.content
  652. # 解析 JSON
  653. import json
  654. try:
  655. start = answer.find("{")
  656. end = answer.rfind("}") + 1
  657. if start >= 0 and end > start:
  658. parsed = json.loads(answer[start:end])
  659. return {"success": True, "data": parsed}
  660. except Exception as e:
  661. logger.warning("解析方案 JSON 失败: %s", e)
  662. return {"success": True, "data": {"raw": answer, "overview": answer[:200]}, "parse_error": str(e)}
  663. except Exception as e:
  664. logger.error("方案生成失败: %s", e)
  665. return {"success": False, "error": str(e)}
  666. @router.post("/health/plan/regenerate-section", response_model=dict)
  667. async def health_plan_regenerate(req: HealthPlanRegenerateRequest):
  668. """重新生成方案的某一个 section"""
  669. java = JavaClient()
  670. llm = ChatOpenAI(
  671. model=settings.llm_model,
  672. api_key=settings.llm_api_key,
  673. base_url=settings.llm_base_url,
  674. temperature=0.3,
  675. )
  676. members_info, all_indicators, kb_results = await _collect_plan_data(java, None, req.member_ids or "", req.goal, req.dimensions or "")
  677. # 构建上下文
  678. ctx_parts = [f"目标: {req.goal}"]
  679. for m in members_info:
  680. ctx_parts.append(f"- {m['name']} (年龄: {m['age']})")
  681. for ind in all_indicators[:10]:
  682. if ind.get("status") in ("abnormal", "high", "low", "偏高", "偏低"):
  683. ctx_parts.append(f"- 【异常】{ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')}")
  684. prompt = REGENERATE_SECTION_SYSTEM_PROMPT
  685. prompt += f"\n\n## 当前 {req.section} 内容\n{req.existing_section_content[:500]}"
  686. prompt += f"\n\n## 用户反馈\n{req.feedback}"
  687. prompt += f"\n\n## 相关背景\n" + "\n".join(ctx_parts[:10])
  688. try:
  689. response = await llm.ainvoke([SystemMessage(content=prompt)])
  690. return {"success": True, "content": response.content}
  691. except Exception as e:
  692. logger.error("重新生成 section 失败: %s", e)
  693. return {"success": False, "error": str(e)}