Explorar o código

restore(batch 13/28): 恢复被误删源码与文档

Agnes Agent hai 2 horas
pai
achega
16cf6aeba2
Modificáronse 100 ficheiros con 13344 adicións e 0 borrados
  1. 34 0
      cfc-frontend/utils/sso.js
  2. 110 0
      cfc-frontend/utils/team-tree.js
  3. 57 0
      cfc-frontend/utils/wuxing-sandbox-mock.js
  4. 140 0
      cfc-frontend/utils/wuxing-sandbox.js
  5. 25 0
      cfc-frontend/vue.config.js
  6. 15 0
      cfc-langgraph/.dockerignore
  7. 26 0
      cfc-langgraph/.env.example
  8. 12 0
      cfc-langgraph/.gitignore
  9. 61 0
      cfc-langgraph/AGENTS.md
  10. 46 0
      cfc-langgraph/Dockerfile
  11. 45 0
      cfc-langgraph/README.md
  12. 0 0
      cfc-langgraph/app/__init__.py
  13. 0 0
      cfc-langgraph/app/agents/__init__.py
  14. 25 0
      cfc-langgraph/app/agents/analysis_agent.py
  15. 35 0
      cfc-langgraph/app/agents/chat_agent.py
  16. 63 0
      cfc-langgraph/app/agents/intent_classifier.py
  17. 55 0
      cfc-langgraph/app/agents/multimodal_agent.py
  18. 977 0
      cfc-langgraph/app/agents/report_parse_agent.py
  19. 0 0
      cfc-langgraph/app/api/__init__.py
  20. 1816 0
      cfc-langgraph/app/api/adapter.py
  21. 50 0
      cfc-langgraph/app/api/analyze.py
  22. 24 0
      cfc-langgraph/app/api/article_quiz.py
  23. 48 0
      cfc-langgraph/app/api/audio.py
  24. 59 0
      cfc-langgraph/app/api/chat.py
  25. 8 0
      cfc-langgraph/app/api/health.py
  26. 64 0
      cfc-langgraph/app/api/indicator_classify.py
  27. 33 0
      cfc-langgraph/app/api/innate_portrait.py
  28. 263 0
      cfc-langgraph/app/api/knowledge_base.py
  29. 38 0
      cfc-langgraph/app/api/logs.py
  30. 355 0
      cfc-langgraph/app/api/meal.py
  31. 56 0
      cfc-langgraph/app/api/portrait.py
  32. 89 0
      cfc-langgraph/app/api/question_generate.py
  33. 42 0
      cfc-langgraph/app/api/recommend.py
  34. 136 0
      cfc-langgraph/app/api/report_parse.py
  35. 54 0
      cfc-langgraph/app/api/self_check.py
  36. 109 0
      cfc-langgraph/app/api/tongue.py
  37. 0 0
      cfc-langgraph/app/audio/__init__.py
  38. 71 0
      cfc-langgraph/app/audio/transcriber.py
  39. 74 0
      cfc-langgraph/app/checkpointer.py
  40. 54 0
      cfc-langgraph/app/config.py
  41. 0 0
      cfc-langgraph/app/graphs/__init__.py
  42. 97 0
      cfc-langgraph/app/graphs/analysis_graph.py
  43. 58 0
      cfc-langgraph/app/graphs/article_quiz_graph.py
  44. 227 0
      cfc-langgraph/app/graphs/chat_graph.py
  45. 327 0
      cfc-langgraph/app/graphs/health_butler_graph.py
  46. 193 0
      cfc-langgraph/app/graphs/health_coach_graph.py
  47. 361 0
      cfc-langgraph/app/graphs/health_plan_graph.py
  48. 67 0
      cfc-langgraph/app/graphs/innate_portrait_graph.py
  49. 159 0
      cfc-langgraph/app/graphs/nutrition_graph.py
  50. 141 0
      cfc-langgraph/app/graphs/portrait_generation_graph.py
  51. 442 0
      cfc-langgraph/app/graphs/question_generation_graph.py
  52. 80 0
      cfc-langgraph/app/graphs/recommend_graph.py
  53. 117 0
      cfc-langgraph/app/graphs/self_check_analysis_graph.py
  54. 77 0
      cfc-langgraph/app/graphs/self_check_trend_graph.py
  55. 0 0
      cfc-langgraph/app/llm/__init__.py
  56. 3 0
      cfc-langgraph/app/llm/client.py
  57. 54 0
      cfc-langgraph/app/log_config.py
  58. 88 0
      cfc-langgraph/app/main.py
  59. 1 0
      cfc-langgraph/app/memory/__init__.py
  60. 59 0
      cfc-langgraph/app/memory/store.py
  61. 140 0
      cfc-langgraph/app/middleware.py
  62. 3 0
      cfc-langgraph/app/models/__init__.py
  63. 13 0
      cfc-langgraph/app/models/article_quiz.py
  64. 18 0
      cfc-langgraph/app/models/chat.py
  65. 19 0
      cfc-langgraph/app/models/common.py
  66. 93 0
      cfc-langgraph/app/models/health_plan.py
  67. 56 0
      cfc-langgraph/app/models/meal.py
  68. 29 0
      cfc-langgraph/app/models/recommend.py
  69. 139 0
      cfc-langgraph/app/monitoring.py
  70. 0 0
      cfc-langgraph/app/parsers/__init__.py
  71. 954 0
      cfc-langgraph/app/parsers/fumat_parser.py
  72. 2036 0
      cfc-langgraph/app/parsers/pdf_parser.py
  73. 110 0
      cfc-langgraph/app/portrait_service.py
  74. 130 0
      cfc-langgraph/app/prompt_service.py
  75. 2 0
      cfc-langgraph/app/rag/__init__.py
  76. 71 0
      cfc-langgraph/app/rag/embeddings.py
  77. 53 0
      cfc-langgraph/app/rag/loader.py
  78. 129 0
      cfc-langgraph/app/rag/microbiome_loader.py
  79. 74 0
      cfc-langgraph/app/rag/retriever.py
  80. 21 0
      cfc-langgraph/app/rag/splitter.py
  81. 0 0
      cfc-langgraph/app/tasks/__init__.py
  82. 225 0
      cfc-langgraph/app/tasks/knowledge_sync.py
  83. 1 0
      cfc-langgraph/app/tools/__init__.py
  84. 284 0
      cfc-langgraph/app/tools/java_client.py
  85. 58 0
      cfc-langgraph/app/tools/product_tools.py
  86. 63 0
      cfc-langgraph/app/tools/report_tools.py
  87. 17 0
      cfc-langgraph/conftest.py
  88. 44 0
      cfc-langgraph/deploy.sh
  89. 71 0
      cfc-langgraph/docker-compose.yml
  90. 97 0
      cfc-langgraph/docs/deployment.md
  91. 121 0
      cfc-langgraph/docs/operations.md
  92. 9 0
      cfc-langgraph/prometheus.yml
  93. 48 0
      cfc-langgraph/pyproject.toml
  94. 21 0
      cfc-langgraph/requirements.txt
  95. 125 0
      cfc-langgraph/requirements_frozen.txt
  96. 82 0
      cfc-langgraph/scripts/run_pytest.sh
  97. 0 0
      cfc-langgraph/src/__init__.py
  98. 89 0
      cfc-langgraph/src/app.py
  99. 2 0
      cfc-langgraph/src/graphs/__init__.py
  100. 177 0
      cfc-langgraph/src/graphs/emotion.py

+ 34 - 0
cfc-frontend/utils/sso.js

@@ -0,0 +1,34 @@
+// 跨小程序单点登录(SSO):从 cfc 跳转到训练营(train)小程序。
+// 复用方式:页面按钮 @click 调 jumpToTrain() 即可;后端已用一次性票据免二次微信授权。
+import { createSsoTicket } from './api.js'
+
+// 训练营小程序 AppID
+const TRAIN_APPID = 'wxcf0ed181fc3bce50'
+// 训练营落地页(App.onLaunch 会读取 query.ssoTicket 换票登录)
+const TRAIN_LANDING_PATH = 'pages/index/index'
+
+/** 已登录用户跳到训练营:签发一次性票据 → navigateToMiniProgram */
+export function jumpToTrain() {
+  if (!uni.getStorageSync('token')) {
+    uni.showToast({ title: '请先登录', icon: 'none' })
+    return
+  }
+  uni.showLoading({ title: '跳转中...' })
+  createSsoTicket('train').then(function(res) {
+    uni.hideLoading()
+    var ticket = res && res.data && res.data.ticket
+    if (!ticket) {
+      uni.showToast({ title: '签发失败,请稍后重试', icon: 'none' })
+      return
+    }
+    uni.navigateToMiniProgram({
+      appId: TRAIN_APPID,
+      path: TRAIN_LANDING_PATH + '?ssoTicket=' + encodeURIComponent(ticket),
+      fail: function() {
+        uni.showToast({ title: '跳转失败,请确认已关联训练营小程序', icon: 'none' })
+      }
+    })
+  }).catch(function() {
+    uni.hideLoading()
+  })
+}

+ 110 - 0
cfc-frontend/utils/team-tree.js

@@ -0,0 +1,110 @@
+/**
+ * 团队层级树工具(纯函数)
+ *
+ * 后端 /api/commission/team/tree 返回扁平 nodes(不含根节点"我"),字段含:
+ * userId/nickname/avatar/level/parentId/referrerId/memberConsumption/myCfEarnedFromMember。
+ *
+ * 注意:后端按 referral_tree 物化表查询(parent_id = 当前用户),
+ * 因此响应里的 parentId 恒为根节点,真正的「直接上级」是 referrerId。
+ * 本模块优先用 referrerId 建立父子关系,缺失时回退 parentId。
+ *
+ * 本模块把扁平数据按父子关系组装成树并拍平成「前序遍历」行,
+ * 供 team.vue 的树形视图(column-reverse 自下而上生长)渲染。
+ */
+
+/**
+ * 取节点直接上级:优先 referrerId,回退 parentId。
+ * @param {Object} node 树节点
+ * @returns {*} 上级 id,无上级时返回 null
+ */
+function directParentId(node) {
+  if (!node) return null
+  if (node.referrerId !== null && node.referrerId !== undefined) return node.referrerId
+  if (node.parentId !== null && node.parentId !== undefined) return node.parentId
+  return null
+}
+
+/**
+ * 将扁平 nodes 构建为前序遍历行。
+ *
+ * @param {Array} nodes 后端返回的扁平节点数组(可为空/undefined)
+ * @param {Array} collapsedIds 已折叠的 userId 列表(其子节点不再输出)
+ * @param {*} rootUserId 根用户("我")id;传入时 L1 节点 depth 从 1 开始
+ * @returns {Array} rows = [{ node, depth, hasChildren, collapsed }]
+ */
+export function buildTeamTreeRows(nodes, collapsedIds, rootUserId) {
+  const list = Array.isArray(nodes) ? nodes : []
+  if (list.length === 0) return []
+
+  const collapseSet = {}
+  const collapsed = Array.isArray(collapsedIds) ? collapsedIds : []
+  for (let i = 0; i < collapsed.length; i++) {
+    collapseSet[String(collapsed[i])] = true
+  }
+
+  // 1. 建立 userId 集合与「直接上级 → children」映射
+  const ids = {}
+  for (let i = 0; i < list.length; i++) {
+    const n = list[i]
+    if (n && n.userId !== null && n.userId !== undefined) ids[String(n.userId)] = true
+  }
+
+  const childrenMap = {}
+  for (let i = 0; i < list.length; i++) {
+    const n = list[i]
+    if (!n || n.userId === null || n.userId === undefined) continue
+    const key = String(n.userId)
+    if (!childrenMap[key]) childrenMap[key] = []
+    const pid = directParentId(n)
+    if (pid !== null && String(pid) !== key) {
+      if (!childrenMap[String(pid)]) childrenMap[String(pid)] = []
+      childrenMap[String(pid)].push(n)
+    }
+  }
+
+  // 2. 根节点:直接上级为空、上级是"我",或上级不在节点集合中
+  const hasRoot = rootUserId !== null && rootUserId !== undefined
+  const rootKey = hasRoot ? String(rootUserId) : null
+  const roots = []
+  for (let i = 0; i < list.length; i++) {
+    const n = list[i]
+    if (!n || n.userId === null || n.userId === undefined) continue
+    const pid = directParentId(n)
+    const isRoot = pid === null ||
+      String(pid) === String(n.userId) ||
+      (hasRoot && String(pid) === rootKey) ||
+      !ids[String(pid)]
+    if (isRoot) roots.push(n)
+  }
+
+  // 3. 前序遍历;折叠节点跳过子节点;visited 防循环
+  const rows = []
+  const visited = {}
+
+  function walk(node, depth) {
+    const key = String(node.userId)
+    if (visited[key]) return
+    visited[key] = true
+
+    const children = childrenMap[key] || []
+    const isCollapsed = !!collapseSet[key]
+    rows.push({
+      node,
+      depth,
+      hasChildren: children.length > 0,
+      collapsed: isCollapsed
+    })
+
+    if (isCollapsed) return
+    for (let i = 0; i < children.length; i++) {
+      walk(children[i], depth + 1)
+    }
+  }
+
+  const rootDepth = hasRoot ? 1 : 0
+  for (let i = 0; i < roots.length; i++) {
+    walk(roots[i], rootDepth)
+  }
+
+  return rows
+}

+ 57 - 0
cfc-frontend/utils/wuxing-sandbox-mock.js

@@ -0,0 +1,57 @@
+/**
+ * 五行能量沙盘 —— 登录前演示数据(mock)。
+ *
+ * 用途:未登录态首页/发现页在用户登录前展示完整的五维能量沙盘(星图 + 维度条 + 成员切换),
+ * 由于此时没有真实的后端数据,使用一组固定演示值。登录后由 /api/energy/sandbox 真实数据替换。
+ *
+ * 数值来源:设计稿 docs/redesign/cfc-home-redesign.html §星图样例
+ * (全家五维能量星图:心 92,身 78,智 74,富 80,行 76,健康指数 82),
+ * 与 wuxing-sandbox.vue 的 prop 结构(scores / overallScore / members / personalData / dimensions)一一对应。
+ *
+ * 约定:scores 为「全家」视角聚合分;personalData 为「本人」视角数据(含 members 数组以定位 self);
+ *       members 为可切换的成员列表(memberId 与 personalData.members[0] 一致者视为本人,切换面板中省略)。
+ */
+
+var WUXING_SANDBOX_MOCK = {
+  // 全家视角五维分(viewMode === 'family' 时读取;overallScore 供 resolveSandboxOverall 读取)
+  scores: {
+    body: 78,
+    mind: 92,
+    wisdom: 74,
+    action: 76,
+    wealth: 80,
+    overallScore: 82
+  },
+  // 太极阳面 / 星图读屏综合分(familyEnergy 与 starAriaLabel 读取)
+  overallScore: 82,
+  // 「本人」视角沙盘数据(viewMode === 'personal' 时读取;members[0] 为 self)
+  personalData: {
+    memberId: 1,
+    name: '小李',
+    bodyScore: 78,
+    mindScore: 92,
+    wisdomScore: 74,
+    actionScore: 76,
+    wealthScore: 80,
+    overallScore: 82,
+    members: [
+      { memberId: 1, name: '小李', bodyScore: 78, mindScore: 92, wisdomScore: 74, actionScore: 76, wealthScore: 80, overallScore: 82 }
+    ]
+  },
+  // 可切换成员列表(成员选择面板:本人 / 各成员 / 全家)
+  members: [
+    { memberId: 1, name: '小李', bodyScore: 78, mindScore: 92, wisdomScore: 74, actionScore: 76, wealthScore: 80, overallScore: 82 },
+    { memberId: 2, name: '爸爸', bodyScore: 70, mindScore: 88, wisdomScore: 79, actionScore: 82, wealthScore: 75, overallScore: 79 },
+    { memberId: 3, name: '妈妈', bodyScore: 82, mindScore: 85, wisdomScore: 81, actionScore: 78, wealthScore: 72, overallScore: 80 }
+  ],
+  // 维度中文名/五行(sortedDimensions 名称与元素来源;缺省时组件内 DIM_META 兜底)
+  dimensions: [
+    { code: 'body', name: '身', element: '土' },
+    { code: 'mind', name: '心', element: '火' },
+    { code: 'wisdom', name: '智', element: '金' },
+    { code: 'action', name: '行', element: '木' },
+    { code: 'wealth', name: '富', element: '水' }
+  ]
+}
+
+export default WUXING_SANDBOX_MOCK

+ 140 - 0
cfc-frontend/utils/wuxing-sandbox.js

@@ -0,0 +1,140 @@
+/**
+ * 五行能量沙盘 — 成员切换与数值解析工具。
+ *
+ * 沙盘里的数据有三类:
+ * - personalData:当前登录用户(或个人视角)的沙盘数据
+ * - members:家庭沙盘返回的所有成员数据
+ * - familyScores:家庭聚合数据
+ *
+ * 组件只负责渲染,成员列表、当前选中项和最终展示分数都通过这里的纯函数解析,
+ * 避免“切换了成员但数值仍是本人”的问题。
+ */
+
+function scoreOf(data) {
+  return {
+    body: data && data.bodyScore != null ? data.bodyScore : 0,
+    mind: data && data.mindScore != null ? data.mindScore : 0,
+    wisdom: data && data.wisdomScore != null ? data.wisdomScore : 0,
+    action: data && data.actionScore != null ? data.actionScore : 0,
+    wealth: data && data.wealthScore != null ? data.wealthScore : 0
+  }
+}
+
+function memberKey(member) {
+  if (!member) return ''
+  if (member.memberId != null) {
+    return String(member.memberId) + '|' + String(member.memberType || '')
+  }
+  return 'name|' + String(member.name || '')
+}
+
+export function dedupeMembers(members) {
+  const list = Array.isArray(members) ? members : []
+  const seen = {}
+  const result = []
+  for (let i = 0; i < list.length; i++) {
+    const member = list[i]
+    if (!member) continue
+    const key = memberKey(member)
+    if (seen[key]) continue
+    seen[key] = true
+    result.push(member)
+  }
+  return result
+}
+
+export function getSelfMember(personalData) {
+  if (!personalData || !Array.isArray(personalData.members) || !personalData.members.length) {
+    return null
+  }
+  return personalData.members[0]
+}
+
+export function findMemberById(members, memberId) {
+  if (memberId == null) return null
+  const list = dedupeMembers(members)
+  for (let i = 0; i < list.length; i++) {
+    if (String(list[i].memberId) === String(memberId)) return list[i]
+  }
+  return null
+}
+
+export function buildMemberOptions(members, personalData) {
+  const self = getSelfMember(personalData)
+  const selfId = self && self.memberId != null ? String(self.memberId) : null
+  const options = [{
+    key: 'personal',
+    label: '本人',
+    viewMode: 'personal',
+    memberId: self && self.memberId != null ? self.memberId : null,
+    member: null
+  }]
+
+  const list = dedupeMembers(members)
+  for (let i = 0; i < list.length; i++) {
+    const member = list[i]
+    if (selfId != null && String(member.memberId) === selfId) continue
+    options.push({
+      key: 'member-' + memberKey(member),
+      label: member.name || '家庭成员',
+      viewMode: 'member',
+      memberId: member.memberId,
+      member
+    })
+  }
+
+  options.push({
+    key: 'family',
+    label: '全家',
+    viewMode: 'family',
+    memberId: null,
+    member: null
+  })
+  return options
+}
+
+export function resolveSandboxScores(viewMode, familyScores, personalData, currentMember) {
+  let source = personalData
+  if (viewMode === 'family') {
+    source = familyScores
+  } else if (viewMode === 'member' && currentMember) {
+    source = currentMember
+  }
+  const s = scoreOf(source)
+  return [s.body, s.mind, s.wisdom, s.action, s.wealth]
+}
+
+export function resolveSandboxOverall(viewMode, familyScores, personalData, currentMember) {
+  let source = personalData
+  if (viewMode === 'family') {
+    source = familyScores
+  } else if (viewMode === 'member' && currentMember) {
+    source = currentMember
+  }
+  return source && source.overallScore != null ? source.overallScore : 0
+}
+
+/**
+ * 太极图中心点击:本人 -> 其他成员 -> 全家 -> 本人。
+ * 找不到当前项时从第一项重新开始,保证不会卡死。
+ */
+export function nextSandboxSelection(options, viewMode, memberId) {
+  const list = Array.isArray(options) && options.length ? options : [
+    { key: 'personal', label: '本人', viewMode: 'personal', memberId: null },
+    { key: 'family', label: '全家', viewMode: 'family', memberId: null }
+  ]
+  let current = -1
+  for (let i = 0; i < list.length; i++) {
+    const option = list[i]
+    if (option.viewMode !== viewMode) continue
+    if (viewMode === 'member' && String(option.memberId) !== String(memberId)) continue
+    current = i
+    break
+  }
+  const next = list[(current + 1) % list.length]
+  return {
+    viewMode: next.viewMode,
+    memberId: next.memberId != null ? next.memberId : null,
+    label: next.label
+  }
+}

+ 25 - 0
cfc-frontend/vue.config.js

@@ -0,0 +1,25 @@
+// vue.config.js - disable thread-loader for compatibility
+// 2026-11-03 H5 部署配置:
+//  - publicPath:生产构建产物以 /frontend/ 为根(配合 cfc.iwintrue.com/frontend 反代);
+//    dev 模式保持 '/'(dev server 直接访问 http://127.0.0.1:8551/ 不受影响)
+//  - devServer.port:uni-app H5 dev server 端口 8081 → 8551(原 8080 被 gogs 占用)
+module.exports = {
+  parallel: false, // Ensure we use the correct source directory
+  publicPath: process.env.NODE_ENV === 'production' ? '/frontend/' : '/',
+  pages: undefined,
+  devServer: {
+    port: 8551
+  },
+  configureWebpack: {
+    resolve: {
+      extensions: ['.vue', '.js', '.json'], // Ensure .vue files resolve correctly
+    },
+    // node:false 会禁用 global/process polyfill,uni-app H5 运行时在浏览器访问 global 报
+    // "global is not defined"(模块 1d50:global.__uniConfig / global["____DA59D6D____"])。
+    // 改用 webpack4 node 配置:注入 global(=> window)与 process,兼容 uni-app H5 运行时。
+    node: {
+      global: true,
+      process: true,
+    },
+  },
+}

+ 15 - 0
cfc-langgraph/.dockerignore

@@ -0,0 +1,15 @@
+.git
+.gitignore
+.venv/bin
+.venv/lib/python3.12/site-packages/__pycache__
+__pycache__
+*.pyc
+*.pyo
+.env
+.env.production
+data/chroma_db
+data/chroma_db_memory
+node_modules
+tests
+docs
+README.md

+ 26 - 0
cfc-langgraph/.env.example

@@ -0,0 +1,26 @@
+# LLM
+LLM_API_KEY=sk-your-key
+LLM_BASE_URL=https://api.deepseek.com/v1
+LLM_MODEL=deepseek-chat
+
+# Embedding
+EMBEDDING_API_KEY=${LLM_API_KEY}
+EMBEDDING_BASE_URL=https://api.deepseek.com/v1
+EMBEDDING_MODEL=text-embedding-v3
+
+# Java Backend
+JAVA_BASE_URL=http://localhost:9082
+JAVA_CONTEXT_URL=${JAVA_BASE_URL}/api/ai/context
+
+# LangSmith (optional)
+LANGCHAIN_TRACING_V2=false
+LANGCHAIN_API_KEY=
+LANGCHAIN_PROJECT=cfc-langgraph
+
+# Service
+SERVICE_HOST=0.0.0.0
+SERVICE_PORT=9000
+LOG_LEVEL=info
+
+# Chroma
+CHROMA_DB_PATH=./data/chroma_db

+ 12 - 0
cfc-langgraph/.gitignore

@@ -0,0 +1,12 @@
+__pycache__/
+*.py[cod]
+.env
+data/
+*.egg-info/
+dist/
+.ruff_cache/
+.pytest_cache/
+
+# Un-ignore .py files (root .gitignore has *.py)
+!*.py
+.venv-bin.tar.gz\n.venv-packages.tar.gz

+ 61 - 0
cfc-langgraph/AGENTS.md

@@ -0,0 +1,61 @@
+# cfc-langgraph
+
+LangGraph Python AI 服务(FastAPI + LangGraph + ChromaDB RAG)。
+
+## AI Agent 配置(Agent 必须遵守)
+
+**Git Author/Committer**: 所有 git commit 操作(含 amend/rebase/merge)的 author 与 committer 均为:
+- name: `zxyj-langgraph`
+- email: `agent@zxyj-lg.com`
+
+**提交规范**: 使用 Conventional Commits 格式(type: description),type 可选值: `feat`、`fix`、`style`、`refactor`、`perf`、`test`、`chore`、`docs`。
+
+**安全限制**:
+- 禁止执行 `git push`(无论 origin 还是任何 remote)
+- 若任务需要推送到远端,必须请求用户授权,由用户自行推送
+- 禁止覆盖远程分支或推送他人提交的代码
+- 本地分支未经验证前,不合并到主分支
+- 任何数据修改操作需先备份或确认影响范围
+
+## 端口
+
+- 本地: 9000(`uvicorn local_report_app:app --port 9000`)
+- 生产: `ai.etotem.com.cn`
+
+## 启动
+
+```powershell
+cd d:\Java_code\CFC\cfc-langgraph
+.\.venv\Scripts\python.exe -m uvicorn local_report_app:app --host 0.0.0.0 --port 9000
+```
+
+## 测试
+
+**⚠️ G-376-1(已闭环)**:系统 `python3` = 3.6.8,无 pytest 模块。
+必须走 venv 解释器,禁止裸用 `python` / `python3`。
+
+**推荐命令**(G-376-2 也一并覆盖):
+
+```bash
+cd /sc-data/cfc/cfc-langgraph
+./scripts/run_pytest.sh                    # 全量 tests/,timeout 600s,日志落盘 /tmp/r*.log
+./scripts/run_pytest.sh tests/test_intent.py   # 单文件
+TIMEOUT_SEC=900 ./scripts/run_pytest.sh    # 自定义超时
+```
+
+**脚本行为**(R376-lg-venv 闭环实现):
+- `VENV_PY=.venv/bin/python` — 强制使用 venv 解释器(Python 3.11.x + pytest 9.1.1)
+- `timeout ${TIMEOUT_SEC}` 默认 600s — 避免 B-325-1 驻留进程在 360s 时强杀于汇总前
+- `tee ${LOG_FILE}` — 输出同时打到 stdout 和 `/tmp/r{run_id}_lg.log`
+- grep 兜底汇总行 — 即使 tee 被截断,仍能从 log_file 提取 passed/failed 计数
+
+**已知红例(环境型,非代码缺陷)**:
+- `test_auto_tag.py` ×3、`test_intent.py` ×3:AgnesAI API 429 配额超限 → 意图分类 fallback 到 `chat`,端点返回 500
+- 解决方式:等待配额刷新后重跑;或将相关用例标记 `pytest.mark.skip(reason="429 rate limit")`
+
+## 技术栈
+
+- Python + FastAPI
+- LangGraph(AI 图谱)
+- ChromaDB(RAG 向量库)
+- 本地仅跑 `local_report_app:app`(最小健康报告解析服务);完整 `app.main:app`(对话/RAG/whisper)走生产

+ 46 - 0
cfc-langgraph/Dockerfile

@@ -0,0 +1,46 @@
+# ── 运行镜像 ──
+FROM python:3.12-slim
+
+ENV TZ=Asia/Shanghai
+RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
+
+WORKDIR /app
+
+# 使用本地 .venv 的 site-packages(已验证包含 gunicorn 26.0.0 / fastapi 0.139.2,
+# 避免构建时从 pypi 重新下载导致版本漂移或网络失败)
+COPY .venv/lib/python3.12/site-packages/ /usr/local/lib/python3.12/site-packages/
+
+COPY app/ app/
+COPY src/ src/
+COPY data/ data/
+
+# 预下载 faster-whisper base 模型(避免启动时慢下载)
+ENV HF_ENDPOINT=https://hf-mirror.com
+RUN python3 -c "from faster_whisper import WhisperModel; WhisperModel('base', device='cpu', compute_type='int8')" 2>/dev/null; \
+    chmod -R u+rwX /root/.cache || true
+
+RUN useradd -m -u 1000 appuser && \
+    mkdir -p /home/appuser/.cache && \
+    cp -a /root/.cache/. /home/appuser/.cache/ && \
+    chown -R appuser:appuser /home/appuser && \
+    chown -R appuser:appuser /app && \
+    mkdir -p /data/chroma_db && \
+    chown -R appuser:appuser /data
+
+# 预置 DeepFace 情绪识别模型(避开 GitHub 下载限速)
+RUN mkdir -p /home/appuser/.deepface/weights && \
+    cp /app/data/deepface-weights/*.h5 /home/appuser/.deepface/weights/ 2>/dev/null || true && \
+    chown -R appuser:appuser /home/appuser/.deepface
+
+USER appuser
+
+EXPOSE 9000
+
+CMD ["python3", "-m", "gunicorn", "app.main:app", \
+     "--worker-class", "uvicorn.workers.UvicornWorker", \
+     "--bind", "0.0.0.0:9000", \
+     "--workers", "1", \
+     "--timeout", "7200", \
+     "--keep-alive", "10", \
+     "--access-logfile", "-", \
+     "--error-logfile", "-"]

+ 45 - 0
cfc-langgraph/README.md

@@ -0,0 +1,45 @@
+# CFC LangGraph 问卷生成服务
+
+关系评估问卷 AI 出题 graph,部署到 `ai.etotem.com.cn`。
+
+## 启动
+
+```bash
+cd cfc-langgraph
+pip install -r requirements.txt
+cp .env.example .env  # 填写 OPENAI_API_KEY / OPENAI_BASE_URL / LLM_MODEL
+uvicorn src.app:app --host 0.0.0.0 --port 9000
+```
+
+## 端点
+
+| Method | Path | 说明 |
+|--------|------|------|
+| GET | `/health` | 健康检查 |
+| POST | `/api/v1/questionnaire/generate` | 生成关系问卷 JSON |
+
+## 测试
+
+```bash
+cd cfc-langgraph
+pytest tests/ -v
+```
+
+## 契约
+
+Request:
+```json
+{
+  "member_name": "小明",
+  "relationship_type": "child",
+  "family_context": {}
+}
+```
+
+Response:
+```json
+{
+  "questionnaire_json": "<stringified JSON>",
+  "version": "20260804115900"
+}
+```

+ 0 - 0
cfc-langgraph/app/__init__.py


+ 0 - 0
cfc-langgraph/app/agents/__init__.py


+ 25 - 0
cfc-langgraph/app/agents/analysis_agent.py

@@ -0,0 +1,25 @@
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class AnalysisAgent:
+    """报告解读 Agent: 拉取报告数据 + 问卷数据 + LLM 分析"""
+
+    def __init__(self):
+        self.java = JavaClient()
+
+    async def get_report_summary(self, report_id: int) -> dict:
+        """获取报告概要 (用于 LLM 上下文)"""
+        try:
+            client = await self.java._get_client()
+            resp = await client.post("/api/health/report/summary", json={
+                "reportId": report_id,
+            })
+            data = resp.json()
+            if data.get("code") == 200:
+                return data.get("data", {})
+        except Exception as e:
+            logger.warning("获取报告概要失败: %s", e)
+        return {}

+ 35 - 0
cfc-langgraph/app/agents/chat_agent.py

@@ -0,0 +1,35 @@
+from typing import Optional
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class ChatAgent:
+    """家庭聊天 Agent: 包装业务逻辑, 被 StateGraph 节点调用"""
+
+    def __init__(self):
+        self.java = JavaClient()
+
+    async def load_context(self, user_id: int, child_id: Optional[int] = None) -> dict:
+        """从 Java 侧加载用户上下文"""
+        params = {}
+        if child_id:
+            params["childId"] = child_id
+        return await self.java.get_user_context(user_id, params)
+
+    async def extract_tasks(self, answer: str, user_id: int, conv_id: str) -> list[dict]:
+        """从 AI 回答中解析 [TASK] 标记"""
+        import re
+        tasks = []
+        pattern = r'\[TASK:\s*\{([^}]+)\}\]'
+        matches = re.findall(pattern, answer)
+        for match in matches:
+            task_info = {}
+            for kv in match.split(","):
+                if ":" in kv:
+                    k, v = kv.split(":", 1)
+                    task_info[k.strip()] = v.strip().strip('"').strip("'")
+            if task_info.get("title"):
+                tasks.append(task_info)
+        return tasks

+ 63 - 0
cfc-langgraph/app/agents/intent_classifier.py

@@ -0,0 +1,63 @@
+from enum import Enum
+from langchain_openai import ChatOpenAI
+from app.config import settings
+from app.prompt_service import get_prompt
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class Intent(str, Enum):
+    CHAT = "chat"           # 日常聊天 / 育儿交流
+    ANALYSIS = "analysis"   # 报告解读 / 数据分析
+    RECOMMEND = "recommend" # 商品 / 活动推荐
+    TASK = "task"           # 任务创建 / 进度查询
+    MIND = "mind"           # 情绪疏导 / 心理支持
+    HEALTH = "health"       # 健康咨询 / 舌诊
+
+
+CLASSIFY_PROMPT = """从用户消息中识别意图, 只返回意图代码, 不要解释:
+
+- chat: 日常聊天、育儿交流、询问建议(非具体商品/报告)
+- analysis: 报告解读\数据分析\趋势查看(提到"报告"/"分析"/"评分")
+- recommend: 商品\活动\文章推荐(提到"推荐"/"买"/"吃什么"/"适合")
+- task: 任务相关(提到"任务"/"打卡"/"完成"/"奖励")
+- mind: 情绪问题\心理支持(提到"心情"/"难过"/"焦虑"/"不开心")
+- health: 健康咨询\舌诊(提到"舌"/"健康"/"体质")
+
+用户消息: {query}
+
+历史上下文: {context}
+
+意图代码:
+"""
+
+
+class IntentClassifier:
+    def __init__(self):
+        self.llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=settings.llm_temperature,
+            max_tokens=20,
+        )
+
+    async def classify(self, query: str, context: str = "") -> Intent:
+        template = await get_prompt("intent_classifier") or CLASSIFY_PROMPT
+        try:
+            prompt = template.format(query=query[:200], context=context[:300])
+        except (KeyError, IndexError, ValueError):
+            logger.warning("Java 配置的 intent_classifier 模板缺少占位符,回退本地模板")
+            prompt = CLASSIFY_PROMPT.format(query=query[:200], context=context[:300])
+        try:
+            resp = await self.llm.ainvoke(prompt)
+            intent_str = resp.content.strip().lower()
+            for intent in Intent:
+                if intent.value in intent_str:
+                    return intent
+            logger.warning("无法识别的意图: %s, 默认 chat", intent_str)
+            return Intent.CHAT
+        except Exception as e:
+            logger.warning("意图分类失败: %s, 默认 chat", e)
+            return Intent.CHAT

+ 55 - 0
cfc-langgraph/app/agents/multimodal_agent.py

@@ -0,0 +1,55 @@
+from typing import Optional
+import logging
+
+from src.graphs.tongue import get_tongue_graph
+
+logger = logging.getLogger(__name__)
+
+
+class TongueDiagnosisAgent:
+    """舌诊分析 Agent — 调用 LangGraph 舌诊 graph(glm-5 视觉模型)"""
+
+    async def diagnose(
+        self,
+        image_url: str,
+        user_id: int,
+        additional_context: Optional[dict] = None,
+        prompt_template: Optional[str] = None,
+    ) -> dict:
+        return await self._via_llm(image_url, prompt_template=prompt_template)
+
+    async def _via_llm(self, image_url: str, prompt_template: Optional[str] = None) -> dict:
+        try:
+            graph = get_tongue_graph()
+            result = graph.invoke({
+                "request": {"image_url": image_url, "prompt_template": prompt_template or ""},
+                "image_base64": None,
+                "raw_response": "",
+                "overall_assessment": "",
+                "indicators": [],
+                "error": None,
+            })
+            if result.get("error"):
+                logger.warning("舌诊 graph 失败: %s", result["error"])
+                return self._mock_result()
+            return {
+                "overall_assessment": result["overall_assessment"],
+                "indicators": result["indicators"],
+            }
+        except Exception as e:
+            logger.warning("舌诊 graph 执行异常: %s", e)
+            return self._mock_result()
+
+    def _mock_result(self) -> dict:
+        return {
+            "overall_assessment": "舌象基本正常, 舌质淡红, 苔薄白, 提示脾胃功能尚可。",
+            "indicators": [
+                {"code": "tongue_color", "value": "淡红"},
+                {"code": "coating_color", "value": "薄白"},
+                {"code": "coating_texture", "value": "润"},
+                {"code": "fissure", "value": "无"},
+                {"code": "teeth_mark", "value": "轻"},
+                {"code": "sublingual_vein", "value": "正常"},
+                {"code": "constitution", "value": "平和质"},
+            ],
+        }

+ 977 - 0
cfc-langgraph/app/agents/report_parse_agent.py

@@ -0,0 +1,977 @@
+"""
+报告解析 Agent:算法解析 + LLM 兜底 + 多类型报告支持
+"""
+import json
+import logging
+import base64
+from typing import Optional
+
+from app.config import settings
+from app.prompt_service import get_prompt
+from app.parsers.pdf_parser import parse_report_pdf_with_fallback
+
+logger = logging.getLogger(__name__)
+
+# ---- LLM 解析提示词模板(Java 系统提示词表可覆盖,动态数据用 {占位符} 由 Python 填充)----
+
+REPORT_PARSE_GENERIC_TEMPLATE = """你是一个通用报告解析专家。请从以下PDF文本中提取结构化数据,返回JSON格式。
+
+报告文本内容:
+{report_text}
+
+请分析这份报告,推断它的类型和内容,然后按以下JSON Schema返回:
+{{
+    "reportType": "推断的报告类型名称",
+    "reportTypeFamily": "报告家族分类(如: dan/cognitive/gut_flora/health_check/other)",
+    "confidence": "high/medium/low",
+    "summary": {{
+        "personName": "姓名",
+        "reportDate": "报告日期",
+        "reportNumber": "报告编号",
+        "overallScore": "总分(如果有)",
+        "interpretation": "报告整体解读摘要"
+    }},
+    "indicators": [
+        {{"name": "指标名称", "value": "数值", "category": "分类", "status": "状态"}}
+    ],
+    "sections": [
+        {{"title": "段落标题", "content": "段落内容摘要", "items": [{{"name": "...", "value": "..."}}]}}
+    ],
+    "textFeatures": ["文本特征1", "文本特征2", ...]
+}}
+
+只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_GUT_TEMPLATE = """你是一个肠道菌群检测报告解析专家。请从以下PDF文本中提取结构化数据,返回JSON格式。
+
+文本内容:
+{report_text}
+
+请按以下JSON Schema返回:
+{{
+    "overview": {{ "person_name": "", "report_number": "", "report_date": "报告日期 yyyy-MM-dd(无法提取则为 null)", "age": 0, "gender": "male/female",
+        "overallScore": 0, "gutHealthScore": 0, "chronicDiseaseScore": 0, "nutritionScore": 0,
+        "gutAge": "", "gutType": "", "gutStatusLevel": "" }},
+    "disease_risks": [{{"name": "", "value": "", "status": "",
+        "related_bacteria": [{{"bacteria": "", "correlation": "", "value": "", "status": ""}}]}}],
+    "nutrition": [{{"name": "", "value": "", "status": ""}}],
+    "amino_acids": [{{"name": "", "value": "", "status": ""}}],
+    "vitamins": [{{"name": "", "value": "", "status": ""}}],
+    "trace_elements": [{{"name": "", "value": "", "status": ""}}]
+}}
+
+只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_BRAIN_TEMPLATE = """你是一个脑状态测量报告解析专家。请从以下文本中提取结构化数据,返回JSON格式。
+
+报告文本内容:
+{report_text}
+
+请按以下JSON Schema返回:
+{{
+    "reportType": "brain_status",
+    "reportTypeFamily": "cognitive",
+    "summary": {{
+        "personName": "姓名",
+        "age": 年龄数字,
+        "gender": "male/female",
+        "reportDate": "报告日期 yyyy-MM-dd",
+        "reportNumber": "报告编号",
+        "overallScore": 综合状态得分数值,
+        "overallLevel": "良好/一般/较差等文字描述"
+    }},
+    "indicators": [
+        {{"name": "指标名称", "value": "数值或等级", "category": "分类", "status": "状态描述"}}
+    ],
+    "sections": [
+        {{
+            "title": "段落标题(如:健康风险评估/疲劳评估/情绪评估/睡眠评估等)",
+            "content": "段落摘要",
+            "items": [
+                {{"name": "子项名称", "value": "数值", "status": "状态/等级"}}
+            ]
+        }}
+    ]
+}}
+
+注意:
+1. 尽量提取所有出现的评估指标,包括:大脑综合状态得分、大脑健康状态得分、大脑能力状态得分、
+   脑供血问题风险、脑供氧问题风险、思维负荷、思维状态风险、大脑疲劳评估、用脑模式、
+   焦虑情绪评估、抑郁情绪评估、抵触情绪评估、安全感评估、情绪管理评估、综合情绪评估、
+   睡眠效果评估等
+2. 数值尽量提取数字,状态文字原样保留
+3. 只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_COGNITIVE_BASIC_TEMPLATE = """你是一个先天智力潜能(皮纹学)测评报告解析专家。请从以下文本中提取基本信息和目录结构,返回JSON格式。
+
+报告文本内容(前5页):
+{report_text}
+
+请按以下JSON Schema返回:
+{{
+    "reportType": "cognitive_aptitude",
+    "reportTypeFamily": "cognitive",
+    "summary": {{
+        "personName": "姓名",
+        "gender": "male/female",
+        "region": "地区",
+        "phone": "电话",
+        "testDate": "测评日期",
+        "birthday": "出生日期",
+        "trc": "TRC值(如107+X+M)",
+        "atd": "ATD角度值",
+        "learningType": "学习类型(听觉型/体觉型/视觉型)",
+        "motivationType": "动机类型",
+        "cognitiveType": "认知类型",
+        "brainDominance": "左脑型/右脑型/全脑型"
+    }},
+    "toc": ["章节1标题", "章节2标题", ...]
+}}
+
+只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_COGNITIVE_INDICATORS_TEMPLATE = """你是一个先天智力潜能(皮纹学)测评报告解析专家。请从以下文本中提取测评指标,返回JSON格式。
+
+报告文本内容(数据页):
+{report_text}
+
+请按以下JSON Schema返回:
+{{
+    "indicators": [
+        {{"name": "指标名称", "value": "数值", "category": "分类", "status": "状态/描述"}}
+    ],
+    "sections": [
+        {{
+            "title": "段落标题(如:智力潜能测评/学习风格测评/左右脑功能/先天性格/八大智能等)",
+            "content": "段落摘要",
+            "items": [{{"name": "子项名称", "value": "数值或描述", "status": "状态"}}]
+        }}
+    ]
+}}
+
+注意:
+1. 指标包括但不限于:TRC(总脊纹数)、ATD(思维敏捷性角)、各脑区指标、
+   八大智能(语言/逻辑数学/空间/身体动觉/音乐/人际/内省/自然观察)、
+   先天学习潜能、先天行为导向、先天学习管道等
+2. 如果某个指标的数值看起来是百分比或数值,直接提取
+3. 只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_COGNITIVE_ADVICE_TEMPLATE = """你是一个先天智力潜能(皮纹学)测评报告解析专家。请从以下文本中提取测评建议和心理学测试结果,返回JSON格式。
+
+报告文本内容(后续页面):
+{report_text}
+
+请按以下JSON Schema返回:
+{{
+    "sections2": [
+        {{
+            "title": "段落标题(如:性格色彩/大五人格/MBTI/学科选择/职业能力/感觉统合等)",
+            "content": "段落摘要",
+            "items": [{{"name": "子项名称", "value": "数值或描述", "status": "状态"}}]
+        }}
+    ],
+    "recommendations": [
+        {{"category": "建议类别", "content": "建议内容"}}
+    ]
+}}
+
+只返回JSON,不要其他文字。"""
+
+REPORT_PARSE_IMAGE_TEMPLATE = """请分析这张报告图片(第{page_idx}页,共{total_pages}页),提取其中的所有结构化数据。
+
+请按以下JSON Schema返回:
+{{
+    "reportType": "推断的报告类型名称",
+    "reportTypeFamily": "报告家族分类(如: gut_flora/health_check/cognitive/brain_status/other)",
+    "summary": {{
+        "personName": "姓名(如果能识别)",
+        "reportDate": "报告日期(如果能识别)",
+        "reportNumber": "报告编号(如果能识别)",
+        "overallScore": "总分(如果可见)",
+        "interpretation": "本页内容摘要"
+    }},
+    "indicators": [
+        {{"name": "指标名称", "value": "数值", "category": "分类", "status": "状态"}}
+    ],
+    "sections": [
+        {{"title": "段落标题", "content": "段落内容摘要", "items": [{{"name": "...", "value": "..."}}]}}
+    ]
+}}
+
+注意:
+1. 请仔细阅读图片中的所有文字,包括表格数据、数值、状态描述
+2. 如果是菌群报告,提取菌属名称、丰度值、参考范围等
+3. 如果是体检报告,提取各项检查指标、数值、参考范围、异常标记
+4. 数值尽量提取精确数字,状态文字原样保留
+5. 只返回JSON,不要其他文字。"""
+
+# 算法解析器使用中文键名(与 extract_full_report_v5.py 一致),
+# Java 消费端期望英文键名;在此做双向映射,Java 读取英文键即可。
+_CN_TO_EN_OVERVIEW: dict[str, str] = {
+    '健康总分': 'overallScore',
+    '菌群健康': 'gutHealthScore',
+    '慢病控制': 'chronicDiseaseScore',
+    '营养均衡': 'nutritionScore',
+    '肠道菌群平衡': 'balanceScore',
+    '菌群多样性': 'diversityScore',
+    '有益菌': 'beneficialScore',
+    '有害菌': 'harmfulScore',
+    '核心菌属': 'coreGenusScore',
+    # V-02 fix: 报告日期相关中文键 → report_date(算法解析器直接产出英文键,此处兼容 LLM 兜底返回中文键)
+    '报告日期': 'report_date',
+    '采样日期': 'report_date',
+    '检测日期': 'report_date',
+}
+
+# 指标分区 → Java 消费端 indicators 的 category(与 Java PdfParseService 兜底路径保持一致)
+_INDICATOR_SECTION_CATEGORY: list[tuple[str, str]] = [
+    ('nutrition', '主要营养评估'),
+    ('amino_acids', '氨基酸评估'),
+    ('vitamins', '维生素评估'),
+    ('trace_elements', '微量元素评估'),
+    ('抗生素风险评估', '抗生素耐药'),
+    ('肠道屏障及代谢物', '肠道屏障功能'),
+    ('短链脂肪酸', '短链脂肪酸'),
+    ('神经递质及激素', '神经递质与激素'),
+]
+
+# 菌群检出详细列表分组 → Java 消费端键
+_FLORA_GROUP_TO_KEY: dict[str, str] = {
+    '核心菌属': 'gut_flora',
+    '益生菌': 'probiotic_species',
+    '菌纲构成': 'taxonomy_class',
+    '菌目构成': 'taxonomy_order',
+    '菌科构成': 'taxonomy_family',
+    '菌属构成': 'taxonomy_genus',
+    '菌种构成': 'taxonomy_species',
+    '病原菌属': 'pathogen_genus',
+    '病原菌检出': 'pathogen_detection',
+}
+
+# Java 端无独立字段、需并入 gut_flora(带 category 区分)的分组
+_FLORA_EXTRA_GROUPS: list[str] = ['有害菌属', '其它重要菌属']
+
+
+def _indicator_constraint(indicators) -> str:
+    """采集指标清单 → LLM 提示词约束块;清单为空时返回空串(保持现状)。"""
+    if not indicators:
+        return ""
+    names = "、".join(str(x) for x in indicators if x)
+    if not names:
+        return ""
+    return (f"\n\n【采集指标约束】请仅提取以下指标项,name 必须与清单一致;"
+            f"报告中缺失的项返回 null,不得臆造:{names}")
+
+
+class ReportParseAgent:
+    """报告解析 Agent"""
+
+    def __init__(self):
+        self.llm_api_key = getattr(settings, 'llm_api_key', '')
+
+    @staticmethod
+    def _normalize_overview_keys(result: dict) -> None:
+        """将 overview 中的中文键名映射为英文键名(双向写入),兼容 Java 消费端。"""
+        overview = result.get('overview')
+        if not overview:
+            return
+        for _cn, _en in _CN_TO_EN_OVERVIEW.items():
+            if _cn in overview and _en not in overview:
+                overview[_en] = overview[_cn]
+
+    @staticmethod
+    def _normalize_for_java(result: dict) -> None:
+        """将算法解析结果归一化为 Java 消费端 snake_case 键。
+
+        保留中文键供调试/LLM 兜底;仅当构建出非空列表时才覆盖 result 对应键,
+        避免覆盖 LLM 兜底直接产出的 indicators/flora/foods。
+        """
+        # 1. indicators:合并各指标分区(含主要消化道致病菌特殊键名)
+        indicators = []
+        for key, category in _INDICATOR_SECTION_CATEGORY:
+            items = result.get(key)
+            if not isinstance(items, list):
+                continue
+            for it in items:
+                if not isinstance(it, dict) or not it.get('name'):
+                    continue
+                indicators.append({
+                    'category': category,
+                    'indicatorName': it['name'],
+                    'indicatorValue': it.get('value', ''),
+                    'unit': '',
+                    'refRange': it.get('refRange', ''),
+                    'status': it.get('status', ''),
+                    'symptoms': '',
+                })
+        for it in result.get('主要消化道致病菌') or []:
+            if not isinstance(it, dict):
+                continue
+            name = it.get('name') or it.get('致病菌')
+            if name:
+                indicators.append({
+                    'category': '主要消化道致病菌',
+                    'indicatorName': name,
+                    'indicatorValue': it.get('value') or it.get('丰度', ''),
+                    'unit': '',
+                    'refRange': '',
+                    'status': it.get('status') or it.get('评估', ''),
+                    'symptoms': '',
+                })
+        if indicators:
+            result['indicators'] = indicators
+
+        # 2. 菌群分组 → snake_case 键(条目字段中文 → 英文)
+        flora = result.get('菌群检出详细列表')
+        if isinstance(flora, dict):
+            for group, en_key in _FLORA_GROUP_TO_KEY.items():
+                converted = []
+                for it in flora.get(group) or []:
+                    if not isinstance(it, dict) or not it.get('名称'):
+                        continue
+                    converted.append({
+                        'name': it['名称'],
+                        'value': it.get('丰度%', ''),
+                        'normal_range': it.get('正常范围%', ''),
+                        'population_level': it.get('人群水平%', ''),
+                        'detection_rate': it.get('检出率%', ''),
+                        'description': it.get('说明', ''),
+                        'category': group,
+                        'level': it.get('水平', ''),
+                    })
+                if converted:
+                    result[en_key] = converted
+            extra = []
+            for group in _FLORA_EXTRA_GROUPS:
+                for it in flora.get(group) or []:
+                    if not isinstance(it, dict) or not it.get('名称'):
+                        continue
+                    extra.append({
+                        'name': it['名称'],
+                        'value': it.get('丰度%', ''),
+                        'normal_range': it.get('正常范围%', ''),
+                        'population_level': it.get('人群水平%', ''),
+                        'detection_rate': it.get('检出率%', ''),
+                        'description': it.get('说明', ''),
+                        'category': group,
+                        'level': it.get('水平', ''),
+                    })
+            if extra:
+                result['gut_flora'] = (result.get('gut_flora') or []) + extra
+
+        # 3. foods:个体化食物推荐表 → snake_case
+        food_table = result.get('个体化食物推荐表')
+        rows = food_table.get('数据') if isinstance(food_table, dict) else food_table
+        foods = []
+        if isinstance(rows, list):
+            for it in rows:
+                if not isinstance(it, dict) or not it.get('名称'):
+                    continue
+                foods.append({
+                    'name': it['名称'],
+                    'category': it.get('分类', ''),
+                    'score': it.get('推荐指数'),
+                    'energy_kj': it.get('能量KJ'),
+                    'protein': it.get('蛋白g'),
+                    'fat': it.get('脂肪g'),
+                    'carbs': it.get('碳水化合物g'),
+                    'starch': it.get('淀粉g'),
+                    'fiber': it.get('总膳食纤维g'),
+                    'cholesterol': it.get('胆固醇mg'),
+                })
+        if foods:
+            result['foods'] = foods
+
+    async def parse(self, file_path: str, indicators: Optional[list] = None) -> dict:
+        """解析 PDF 报告,算法解析 + LLM 兜底"""
+        # 1. 算法解析
+        result = parse_report_pdf_with_fallback(file_path)
+        logger.info("算法解析完成: format=%s, overview_keys=%d",
+                     result.get('format'), len(result.get('overview', {})))
+
+        # 1.5 归一化 overview 键名:中文 → 英文(Java 消费端兼容)
+        self._normalize_overview_keys(result)
+        # 1.6 归一化指标/菌群/食物为 Java 消费端 snake_case 键
+        self._normalize_for_java(result)
+
+        # 2. 如果解析不完整,LLM 兜底
+        if result.get('_parse_incomplete') or not result.get('disease_risks'):
+            logger.info("算法解析不完整,尝试 LLM 兜底")
+            llm_result = await self._parse_with_llm(file_path, indicators)
+            if llm_result:
+                # 合并 LLM 结果到算法结果上(LLM 覆盖缺失字段)
+                for key in ['disease_risks', 'nutrition', 'amino_acids',
+                            'vitamins', 'trace_elements', 'indicators']:
+                    if key in llm_result and not result.get(key):
+                        result[key] = llm_result[key]
+                if llm_result.get('overview'):
+                    for k, v in llm_result['overview'].items():
+                        if k not in result.get('overview', {}):
+                            result.setdefault('overview', {})[k] = v
+                # 重新归一化:LLM 补齐的分区也要并入 indicators
+                self._normalize_for_java(result)
+
+        # 清理内部标记
+        result.pop('_parse_incomplete', None)
+        return result
+
+    async def parse_generic(self, file_path: str, extra_context: Optional[dict] = None,
+                            indicators: Optional[list] = None) -> dict:
+        """通用报告 LLM 解析(不经过算法解析,直接走 LLM)"""
+        try:
+            from PyPDF2 import PdfReader
+            reader = PdfReader(file_path)
+            text = '\n'.join(page.extract_text() or '' for page in reader.pages)
+
+            ctx_str = ""
+            if extra_context:
+                ctx_str = f"\n额外上下文:{json.dumps(extra_context, ensure_ascii=False)}"
+
+            template = await get_prompt("report_parse_generic") or REPORT_PARSE_GENERIC_TEMPLATE
+            prompt = template.format(report_text=text[:12000] + ctx_str) + _indicator_constraint(indicators)
+
+            if self.llm_api_key:
+                import httpx
+                async with httpx.AsyncClient(timeout=120) as client:
+                    resp = await client.post(
+                        f"{settings.llm_base_url}/chat/completions",
+                        json={
+                            "model": settings.llm_model or "gpt-4o",
+                            "messages": [{"role": "user", "content": prompt}],
+                            "temperature": 0.1,
+                        },
+                        headers={"Authorization": f"Bearer {self.llm_api_key}"},
+                    )
+                    resp.raise_for_status()
+                    data = resp.json()
+                    content = data['choices'][0]['message']['content']
+                    content = content.replace('```json', '').replace('```', '').strip()
+                    return json.loads(content)
+            else:
+                logger.warning("LLM 未配置,返回空")
+                return {"reportType": "unknown", "summary": {}, "indicators": [], "sections": []}
+        except Exception as e:
+            logger.error("通用LLM解析失败: %s", e)
+            return {"reportType": "unknown", "error": str(e), "summary": {}, "indicators": [], "sections": []}
+
+    async def _parse_with_llm(self, file_path: str, indicators: Optional[list] = None) -> Optional[dict]:
+        """LLM 兜底解析"""
+        try:
+            from PyPDF2 import PdfReader
+            reader = PdfReader(file_path)
+            text = '\n'.join(page.extract_text() or '' for page in reader.pages)
+
+            template = await get_prompt("report_parse_gut") or REPORT_PARSE_GUT_TEMPLATE
+            prompt = template.format(report_text=text[:8000]) + _indicator_constraint(indicators)
+
+            if self.llm_api_key:
+                # 调 OpenAI 兼容 API
+                import httpx
+                async with httpx.AsyncClient(timeout=60) as client:
+                    resp = await client.post(
+                        f"{settings.llm_base_url}/chat/completions",
+                        json={
+                            "model": settings.llm_model or "gpt-4o",
+                            "messages": [{"role": "user", "content": prompt}],
+                            "temperature": 0.1,
+                        },
+                        headers={"Authorization": f"Bearer {self.llm_api_key}"},
+                    )
+                    resp.raise_for_status()
+                    data = resp.json()
+                    content = data['choices'][0]['message']['content']
+                    content = content.replace('```json', '').replace('```', '').strip()
+                    return json.loads(content)
+            else:
+                logger.warning("LLM 未配置,跳过 LLM 兜底")
+                return None
+        except Exception as e:
+            logger.warning("LLM 解析失败: %s", e)
+            return None
+
+    # ================================================================
+    # 多类型报告解析
+    # ================================================================
+
+    async def parse_by_type(self, file_path: str, report_type: str,
+                            extra_context: Optional[dict] = None,
+                            indicators: Optional[list] = None) -> dict:
+        """按报告类型路由到专用解析器。
+
+        :param file_path: PDF 文件路径
+        :param report_type: 报告类型标识:
+            - "brain_status": 脑状态测量报告
+            - "cognitive_aptitude": 先天智力潜能/皮纹学测评报告
+            - "scanned_image": 扫描图片 PDF(无文字层,需多模态 LLM)
+            - "auto": 自动检测类型
+        :return: 结构化解析结果 dict
+        """
+        if report_type == "auto":
+            report_type = self._detect_report_type(file_path)
+            logger.info("自动检测报告类型: %s", report_type)
+
+        if report_type == "brain_status":
+            return await self._parse_brain_status(file_path)
+        elif report_type == "cognitive_aptitude":
+            return await self._parse_cognitive_aptitude(file_path)
+        elif report_type == "scanned_image":
+            return await self._parse_scanned_image(file_path)
+        else:
+            logger.info("未识别的报告类型 %s,走通用解析", report_type)
+            return await self.parse_generic(file_path, extra_context, indicators)
+
+    # ---- 格式检测 ----
+
+    def _detect_report_type(self, file_path: str) -> str:
+        """根据 PDF 文本内容自动检测报告类型。"""
+        try:
+            from PyPDF2 import PdfReader
+            reader = PdfReader(file_path)
+
+            # 检测是否有可提取文本
+            total_text = ""
+            for i in range(min(12, len(reader.pages))):
+                t = reader.pages[i].extract_text() or ""
+                total_text += t
+
+            if len(total_text.strip()) < 20:
+                # 前几页几乎无文字 → 可能是扫描图片 PDF
+                return "scanned_image"
+
+            # 脑状态测量报告
+            if "脑状态测量报告" in total_text or "大脑综合状态" in total_text:
+                return "brain_status"
+
+            # 智力潜能 / 皮纹学报告
+            if ("先天数据" in total_text or "智力潜能" in total_text
+                    or "皮纹" in total_text or "ATD" in total_text
+                    or "trc" in total_text.lower()):
+                return "cognitive_aptitude"
+
+            # 北京肠道菌群报告
+            if ("肠道菌群检测" in total_text and "高通量测序" in total_text):
+                return "gut_flora_beijing"
+
+            return "generic"
+        except Exception as e:
+            logger.warning("报告类型检测失败: %s", e)
+            return "generic"
+
+    # ---- 通用 LLM 调用 ----
+
+    async def _call_llm(self, prompt: str, timeout: int = 120) -> str:
+        """调用 LLM 并返回文本响应。
+
+        :raises RuntimeError: LLM 未配置或调用失败
+        """
+        if not self.llm_api_key:
+            raise RuntimeError("LLM 未配置")
+        import httpx
+        async with httpx.AsyncClient(timeout=timeout) as client:
+            resp = await client.post(
+                f"{settings.llm_base_url}/chat/completions",
+                json={
+                    "model": settings.llm_model or "gpt-4o",
+                    "messages": [{"role": "user", "content": prompt}],
+                    "temperature": 0.1,
+                },
+                headers={"Authorization": f"Bearer {self.llm_api_key}"},
+            )
+            resp.raise_for_status()
+            data = resp.json()
+            content = data['choices'][0]['message']['content']
+            return content.replace('```json', '').replace('```', '').strip()
+
+    async def _call_llm_vision(self, prompt: str, image_base64: str,
+                               timeout: int = 180) -> str:
+        """调用多模态 LLM(vision),传入图片 + 文字提示。
+
+        :raises RuntimeError: LLM 未配置或调用失败
+        """
+        if not self.llm_api_key:
+            raise RuntimeError("LLM 未配置")
+        import httpx
+        async with httpx.AsyncClient(timeout=timeout) as client:
+            resp = await client.post(
+                f"{settings.llm_base_url}/chat/completions",
+                json={
+                    "model": settings.llm_model or "gpt-4o",
+                    "messages": [
+                        {
+                            "role": "user",
+                            "content": [
+                                {"type": "text", "text": prompt},
+                                {
+                                    "type": "image_url",
+                                    "image_url": {
+                                        "url": f"data:image/png;base64,{image_base64}",
+                                    },
+                                },
+                            ],
+                        }
+                    ],
+                    "temperature": 0.1,
+                },
+                headers={"Authorization": f"Bearer {self.llm_api_key}"},
+            )
+            resp.raise_for_status()
+            data = resp.json()
+            content = data['choices'][0]['message']['content']
+            return content.replace('```json', '').replace('```', '').strip()
+
+    def _pdf_to_text(self, file_path: str, max_pages: int = 0) -> str:
+        """用 PyPDF2 提取 PDF 全文。max_pages=0 表示全部。"""
+        from PyPDF2 import PdfReader
+        reader = PdfReader(file_path)
+        n = len(reader.pages) if max_pages == 0 else min(max_pages, len(reader.pages))
+        return '\n'.join(reader.pages[i].extract_text() or '' for i in range(n))
+
+    # ---- 1. 脑状态测量报告 ----
+
+    async def _parse_brain_status(self, file_path: str) -> dict:
+        """解析脑状态测量报告。
+
+        文本可提取,数据清晰。使用 LLM 提取结构化数据。
+
+        返回结构:
+        {
+            "reportType": "brain_status",
+            "reportTypeFamily": "cognitive",
+            "summary": {
+                "personName": "张文远",
+                "age": 44,
+                "gender": "male",
+                "reportDate": "2026-05-03",
+                "reportNumber": "CL79474",
+                "overallScore": 82.1,
+                "overallLevel": "良好",
+            },
+            "indicators": [
+                {"name": "大脑综合状态得分", "value": "82.1", "category": "综合评分", "status": "良好"},
+                {"name": "脑供血问题风险评估", "value": "低风险", "category": "风险评估", "status": "低风险"},
+                ...
+            ],
+            "sections": [
+                {"title": "疲劳评估", "content": "...", "items": [...]},
+                {"title": "情绪评估", "content": "...", "items": [...]},
+                {"title": "睡眠评估", "content": "...", "items": [...]},
+            ]
+        }
+        """
+        logger.info("开始解析脑状态测量报告: %s", file_path)
+        text = self._pdf_to_text(file_path)
+
+        template = await get_prompt("report_parse_brain") or REPORT_PARSE_BRAIN_TEMPLATE
+        prompt = template.format(report_text=text)
+
+        try:
+            content = await self._call_llm(prompt, timeout=120)
+            result = json.loads(content)
+            logger.info("脑状态报告解析完成: indicators=%d, sections=%d",
+                        len(result.get('indicators', [])),
+                        len(result.get('sections', [])))
+            return result
+        except Exception as e:
+            logger.error("脑状态报告解析失败: %s", e)
+            return {
+                "reportType": "brain_status",
+                "reportTypeFamily": "cognitive",
+                "error": str(e),
+                "summary": {},
+                "indicators": [],
+                "sections": [],
+            }
+
+    # ---- 2. 智力潜能 / 皮纹学测评报告 ----
+
+    async def _parse_cognitive_aptitude(self, file_path: str) -> dict:
+        """解析先天智力潜能/皮纹学测评报告。
+
+        115页,文本碎片化严重。分块提取 + LLM 合并。
+
+        返回结构:
+        {
+            "reportType": "cognitive_aptitude",
+            "reportTypeFamily": "cognitive",
+            "summary": {
+                "personName": "张老师",
+                "gender": "male",
+                "region": "北京",
+                "phone": "15901552192",
+                "testDate": "2026-04-03",
+                "birthday": "1982-02-06",
+            },
+            "indicators": [
+                {"name": "TRC", "value": "107+X+M", "category": "先天数据", "status": ""},
+                {"name": "ATD", "value": "35.5", "category": "思维敏捷性", "status": "超级敏感型"},
+                ...
+            ],
+            "sections": [
+                {"title": "智力潜能测评", "content": "...", "items": [...]},
+                {"title": "学习风格测评", "content": "...", "items": [...]},
+                {"title": "八大智能测试", "content": "...", "items": [...]},
+                ...
+            ]
+        }
+        """
+        logger.info("开始解析智力潜能测评报告: %s", file_path)
+
+        from PyPDF2 import PdfReader
+        reader = PdfReader(file_path)
+        total_pages = len(reader.pages)
+
+        # 分块提取文本 — 每块约 8000 字符
+        all_pages = []
+        for i in range(total_pages):
+            t = reader.pages[i].extract_text() or ''
+            all_pages.append((i + 1, t))
+
+        # 合并前 5 页(基本信息区)作为第一块
+        first_chunk = '\n'.join(t for _, t in all_pages[:5])
+        # 合并中间数据页(6-60页)作为第二块
+        mid_chunk = '\n'.join(t for _, t in all_pages[5:min(30, len(all_pages))])
+        # 合并后续页(30-62页有文字的)
+        later_chunk = '\n'.join(t for _, t in all_pages[30:min(62, len(all_pages))])
+
+        # 第一块: 基本信息 + 目录
+        template1 = await get_prompt("report_parse_cognitive_basic") or REPORT_PARSE_COGNITIVE_BASIC_TEMPLATE
+        prompt1 = template1.format(report_text=first_chunk)
+
+        # 第二块: 智力潜能/学习风格/八大智能等核心数据
+        template2 = await get_prompt("report_parse_cognitive_indicators") or REPORT_PARSE_COGNITIVE_INDICATORS_TEMPLATE
+        prompt2 = template2.format(report_text=mid_chunk)
+
+        # 第三块: 后续章节(学科建议/职业建议/心理学测试等)
+        template3 = await get_prompt("report_parse_cognitive_advice") or REPORT_PARSE_COGNITIVE_ADVICE_TEMPLATE
+        prompt3 = template3.format(report_text=later_chunk)
+
+        result = {
+            "reportType": "cognitive_aptitude",
+            "reportTypeFamily": "cognitive",
+            "summary": {},
+            "indicators": [],
+            "sections": [],
+        }
+
+        try:
+            # 并行请求三块
+            import asyncio
+            tasks = []
+            if first_chunk.strip():
+                tasks.append(self._call_llm(prompt1, timeout=120))
+            if mid_chunk.strip():
+                tasks.append(self._call_llm(prompt2, timeout=120))
+            if later_chunk.strip():
+                tasks.append(self._call_llm(prompt3, timeout=120))
+
+            responses = await asyncio.gather(*tasks, return_exceptions=True)
+
+            # 合并结果
+            for i, resp in enumerate(responses):
+                if isinstance(resp, Exception):
+                    logger.warning("智力潜能报告第%d块解析失败: %s", i + 1, resp)
+                    continue
+                try:
+                    chunk_result = json.loads(str(resp))
+                    if i == 0:
+                        # 第一块: summary + toc
+                        result['summary'] = chunk_result.get('summary', {})
+                        result['toc'] = chunk_result.get('toc', [])
+                    elif i == 1:
+                        # 第二块: indicators + sections
+                        result['indicators'] = chunk_result.get('indicators', [])
+                        result['sections'] = chunk_result.get('sections', [])
+                    elif i == 2:
+                        # 第三块: sections2 + recommendations
+                        if chunk_result.get('sections2'):
+                            result['sections'].extend(chunk_result['sections2'])
+                        if chunk_result.get('recommendations'):
+                            result['recommendations'] = chunk_result['recommendations']
+                except (json.JSONDecodeError, KeyError) as e:
+                    logger.warning("智力潜能报告第%d块JSON解析失败: %s", i + 1, e)
+
+            logger.info("智力潜能报告解析完成: indicators=%d, sections=%d",
+                        len(result.get('indicators', [])),
+                        len(result.get('sections', [])))
+            return result
+        except Exception as e:
+            logger.error("智力潜能报告解析失败: %s", e)
+            return result
+
+    # ---- 3. 扫描图片 PDF(多模态 LLM) ----
+
+    async def _parse_scanned_image(self, file_path: str) -> dict:
+        """解析扫描图片 PDF(无文字层)。
+
+        流程:
+        1. 用 PyPDF2 提取页面图片(base64 编码)
+        2. 逐页发送给多模态 LLM 进行 OCR + 结构化提取
+        3. 合并各页结果
+
+        返回结构与 parse_generic 一致:
+        {
+            "reportType": "推断的类型",
+            "reportTypeFamily": "报告家族",
+            "summary": {...},
+            "indicators": [...],
+            "sections": [...]
+        }
+        """
+        logger.info("开始解析扫描图片PDF: %s", file_path)
+
+        from PyPDF2 import PdfReader
+        reader = PdfReader(file_path)
+        total_pages = len(reader.pages)
+
+        all_indicators = []
+        all_sections = []
+        summary = {}
+        detected_type = "unknown"
+
+        for page_idx in range(total_pages):
+            page = reader.pages[page_idx]
+            image_b64 = self._extract_page_image_base64(page)
+            if not image_b64:
+                logger.warning("第%d页无图片可提取", page_idx + 1)
+                continue
+
+            template = await get_prompt("report_parse_image") or REPORT_PARSE_IMAGE_TEMPLATE
+            prompt = template.format(page_idx=page_idx + 1, total_pages=total_pages)
+
+            try:
+                content = await self._call_llm_vision(prompt, image_b64, timeout=180)
+                page_result = json.loads(content)
+
+                # 合并指标
+                if page_result.get('indicators'):
+                    all_indicators.extend(page_result['indicators'])
+
+                # 合并段落
+                if page_result.get('sections'):
+                    all_sections.extend(page_result['sections'])
+
+                # 合并基本信息(第一页优先)
+                if page_idx == 0 and page_result.get('summary'):
+                    summary = page_result['summary']
+
+                # 更新检测到的类型
+                if page_result.get('reportType') and detected_type == "unknown":
+                    detected_type = page_result['reportType']
+
+                logger.info("扫描PDF第%d页解析完成: indicators=%d",
+                            page_idx + 1, len(page_result.get('indicators', [])))
+            except Exception as e:
+                logger.warning("扫描PDF第%d页解析失败: %s", page_idx + 1, e)
+
+        result = {
+            "reportType": detected_type,
+            "reportTypeFamily": "other",
+            "summary": summary,
+            "indicators": all_indicators,
+            "sections": all_sections,
+        }
+
+        logger.info("扫描图片PDF解析完成: pages=%d, indicators=%d, sections=%d",
+                    total_pages, len(all_indicators), len(all_sections))
+        return result
+
+    def _extract_page_image_base64(self, page) -> str:
+        """从 PDF 页面对象中提取图片,返回 base64 编码字符串。
+
+        支持以下情况:
+        - 页面包含 /XObject 中的 /Image 类型对象
+        - 页面是整页图片(常见于扫描件)
+
+        :return: base64 编码的 PNG 图片,或空字符串(无图片)
+        """
+        try:
+            from PyPDF2 import PdfReader
+            import io
+
+            # 获取页面资源
+            resources = page.get('/Resources')
+            if not resources:
+                return ""
+
+            x_objects = resources.get('/XObject')
+            if not x_objects:
+                return ""
+
+            x_obj = x_objects.get_object()
+
+            # 找最大的图片对象
+            best_image = None
+            best_size = 0
+
+            for name in x_obj:
+                obj = x_obj[name]
+                obj_resolved = obj.get_object()
+
+                subtype = obj_resolved.get('/Subtype')
+                if subtype != '/Image':
+                    continue
+
+                width = int(obj_resolved.get('/Width', 0))
+                height = int(obj_resolved.get('/Height', 0))
+                size = width * height
+
+                if size > best_size:
+                    best_size = size
+                    best_image = obj_resolved
+
+            if not best_image:
+                return ""
+
+            # 提取图片数据
+            color_space = best_image.get('/ColorSpace', '/DeviceRGB')
+            bits_per_component = int(best_image.get('/BitsPerComponent', 8))
+            width = int(best_image.get('/Width', 0))
+            height = int(best_image.get('/Height', 0))
+
+            raw_data = best_image.get_data()
+
+            # 转换为 PIL Image → PNG → base64
+            # 尝试安装 Pillow(如果没有)
+            try:
+                from PIL import Image
+            except ImportError:
+                logger.warning("Pillow 未安装,尝试基础 base64 编码")
+                # 如果没有 Pillow,直接 base64 编码原始数据
+                return base64.b64encode(raw_data).decode('utf-8')
+
+            # 根据 ColorSpace 确定模式
+            if isinstance(color_space, str):
+                if 'RGB' in color_space or 'RGB' in str(color_space):
+                    mode = 'RGB'
+                elif 'Gray' in color_space or 'Gray' in str(color_space):
+                    mode = 'L'
+                elif 'CMYK' in color_space:
+                    mode = 'CMYK'
+                else:
+                    mode = 'RGB'
+            else:
+                mode = 'RGB'
+
+            if width > 0 and height > 0:
+                img = Image.frombytes(mode, (width, height), raw_data)
+
+                # CMYK → RGB
+                if mode == 'CMYK':
+                    img = img.convert('RGB')
+
+                # 缩小图片以减少 token 消耗(最大 2000px 边)
+                max_dim = 2000
+                if max(width, height) > max_dim:
+                    ratio = max_dim / max(width, height)
+                    new_size = (int(width * ratio), int(height * ratio))
+                    img = img.resize(new_size, Image.LANCZOS)
+
+                # 转 PNG
+                buf = io.BytesIO()
+                img.save(buf, format='PNG', optimize=True)
+                return base64.b64encode(buf.getvalue()).decode('utf-8')
+
+            return ""
+        except Exception as e:
+            logger.warning("提取页面图片失败: %s", e)
+            return ""

+ 0 - 0
cfc-langgraph/app/api/__init__.py


+ 1816 - 0
cfc-langgraph/app/api/adapter.py

@@ -0,0 +1,1816 @@
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, ConfigDict, AliasChoices, Field
+from typing import Optional, List, Dict, Any
+from app.graphs.chat_graph import create_chat_graph
+from app.graphs.analysis_graph import create_analysis_graph
+from app.graphs.health_coach_graph import create_health_coach_graph
+from app.graphs.health_butler_graph import create_health_butler_graph
+from app.graphs.nutrition_graph import create_nutrition_graph
+from app.tools.java_client import JavaClient
+from app.rag.retriever import RagRetriever
+from app.config import settings
+from app.prompt_service import get_prompt
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.models.health_plan import HealthPlanResponse, PlanTask, MultiMemberPlanResponse, PlanPart, HealthPlanSection
+import uuid
+import time
+import re
+import logging
+import json
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/v1", tags=["adapter"])
+
+# ---- Dify-compatible request/response models ----
+
+class DifyMessage(BaseModel):
+    role: str
+    content: str
+
+class DifyChatRequest(BaseModel):
+    # 前端 userId/conversationId 可能为数字,允许 int/float 自动转 str,避免 422
+    model_config = ConfigDict(coerce_numbers_to_str=True)
+    query: str = ""
+    user: str = "anonymous"
+    conversation_id: str = ""
+    messages: list[DifyMessage] = []
+    inputs: dict = {}
+    response_mode: str = "blocking"  # blocking / streaming
+    user_id: str = ""
+    bot_name: str = "AI管家"
+
+class DifyAnalysisRequest(BaseModel):
+    # 前端 userId 可能为数字,允许 int/float 自动转 str,避免 422
+    model_config = ConfigDict(coerce_numbers_to_str=True)
+    report_id: Optional[int] = None
+    user_id: Optional[str] = None
+    focus: Optional[str] = None
+    messages: list[DifyMessage] = []
+    inputs: dict = {}
+
+class HealthCoachGenerateRequest(BaseModel):
+    """Java 后端健康方案生成专用请求体"""
+    family_id: Optional[int] = None
+    member_ids: Optional[str] = None
+    dimensions: Optional[str] = None
+    goal: str = ""
+
+class DifyChoice(BaseModel):
+    index: int
+    message: dict
+    finish_reason: str = "stop"
+
+class DifyUsage(BaseModel):
+    prompt_tokens: int = 0
+    completion_tokens: int = 0
+    total_tokens: int = 0
+
+class DifyResponse(BaseModel):
+    id: str
+    object: str = "chat.completion"
+    created: int
+    model: str = "langgraph-cfc"
+    choices: list[DifyChoice]
+    usage: DifyUsage = DifyUsage()
+    metadata: dict = {}
+
+# ---- Helpers ----
+
+def _now_ts() -> int:
+    return int(time.time())
+
+def _extract_query(req: DifyChatRequest) -> str:
+    if req.query:
+        return req.query
+    # fallback: take last user message
+    for msg in reversed(req.messages):
+        if msg.role == "user":
+            return msg.content
+    return ""
+
+def _to_langgraph_context(req: DifyChatRequest) -> dict:
+    ctx = {}
+    if isinstance(req.inputs, dict):
+        ctx["child_id"] = req.inputs.get("child_id")
+        ctx["report_id"] = req.inputs.get("report_id")
+        ctx["family_id"] = req.inputs.get("family_id")
+    return ctx
+
+# ---- Dify-compatible endpoints ----
+
+@router.post("/chat/completion", response_model=DifyResponse)
+async def chat_completion(req: DifyChatRequest):
+    query = _extract_query(req)
+    if not query:
+        raise HTTPException(status_code=400, detail="query 为空")
+
+    graph = create_chat_graph()
+    initial_state = {
+        "query": query,
+        "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
+        "conversation_id": req.conversation_id or None,
+        "intent": None,
+        "context": _to_langgraph_context(req),
+        "messages": None,
+        "answer": None,
+        "tasks": [],
+        "sources": [],
+    }
+    config = {
+        "configurable": {"thread_id": req.conversation_id or str(req.user_id or "default")},
+    }
+    result = await graph.ainvoke(initial_state, config)
+    answer = result.get("answer") or ""
+    return DifyResponse(
+        id=f"chatcmpl-{uuid.uuid4().hex[:24]}",
+        created=_now_ts(),
+        choices=[
+            DifyChoice(
+                index=0,
+                message={"role": "assistant", "content": answer},
+                finish_reason="stop",
+            )
+        ],
+        usage=DifyUsage(
+            prompt_tokens=len(query.split()),
+            completion_tokens=len(answer.split()),
+            total_tokens=len(query.split()) + len(answer.split()),
+        ),
+    )
+
+
+@router.post("/analysis/run", response_model=DifyResponse)
+async def analysis_run(req: DifyAnalysisRequest):
+    graph = create_analysis_graph()
+    report_id = req.report_id
+    if report_id is None and isinstance(req.inputs, dict):
+        report_id = req.inputs.get("report_id")
+    initial_state = {
+        "report_id": report_id,
+        "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
+        "focus": req.focus,
+        "report_data": None,
+        "survey_data": None,
+        "dimension_scores": None,
+        "analysis": None,
+        "recommendations": [],
+    }
+    result = await graph.ainvoke(initial_state, {})
+    analysis = result.get("analysis") or ""
+    recommendations = result.get("recommendations") or []
+    content = analysis
+    if recommendations:
+        content += "\n\n建议:\n" + "\n".join(f"- {r}" for r in recommendations)
+    return DifyResponse(
+        id=f"analysis-{uuid.uuid4().hex[:24]}",
+        created=_now_ts(),
+        choices=[
+            DifyChoice(
+                index=0,
+                message={"role": "assistant", "content": content},
+                finish_reason="stop",
+            )
+        ],
+        usage=DifyUsage(
+            prompt_tokens=len((req.focus or "").split()),
+            completion_tokens=len(content.split()),
+            total_tokens=len((req.focus or "").split()) + len(content.split()),
+        ),
+    )
+
+
+@router.post("/health/coach", response_model=DifyResponse)
+async def health_coach(req: DifyChatRequest):
+    query = _extract_query(req)
+    if not query:
+        raise HTTPException(status_code=400, detail="query 为空")
+
+    graph = create_health_coach_graph()
+    initial_state = {
+        "query": query,
+        "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
+        "child_id": int(req.inputs.get("child_id")) if req.inputs.get("child_id") else None,
+        "conversation_id": req.conversation_id or None,
+        "context": _to_langgraph_context(req),
+        "answer": None,
+        "sources": [],
+        "memory_messages": None,
+    }
+    config = {
+        "configurable": {"thread_id": req.conversation_id or f"health_{req.user_id}"},
+    }
+    result = await graph.ainvoke(initial_state, config)
+    answer = result.get("answer") or ""
+
+    sources = result.get("sources") or []
+    metadata = {}
+    if sources:
+        metadata["sources"] = [
+            {"title": s.get("title", ""), "type": s.get("type", "knowledge")}
+            for s in sources
+        ]
+
+    return DifyResponse(
+        id=f"health-{uuid.uuid4().hex[:24]}",
+        created=_now_ts(),
+        model="langgraph-health-coach",
+        choices=[
+            DifyChoice(
+                index=0,
+                message={"role": "assistant", "content": answer},
+                finish_reason="stop",
+            )
+        ],
+        usage=DifyUsage(
+            prompt_tokens=len(query.split()),
+            completion_tokens=len(answer.split()),
+            total_tokens=len(query.split()) + len(answer.split()),
+        ),
+        metadata=metadata,
+    )
+
+
+@router.post("/health/butler", response_model=DifyResponse)
+async def health_butler(req: DifyChatRequest):
+    """AI 健康管家 — 基于健康知识库检索 + 个性化建议 + 任务生成"""
+    query = _extract_query(req)
+    if not query:
+        raise HTTPException(status_code=400, detail="query 为空")
+
+    graph = create_health_butler_graph()
+
+    # 从 inputs 中提取健康管家需要的上下文
+    inputs = req.inputs or {}
+    family_id = inputs.get("family_id")
+    child_id = inputs.get("child_id")
+    report_id = inputs.get("report_id")
+    focus = inputs.get("focus")
+
+    # conversation_id 用于 checkpointer thread
+    thread_id = req.conversation_id or f"butler_{req.user_id or 'anon'}"
+
+    initial_state = {
+        "query": query,
+        "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
+        "conversation_id": thread_id,
+        "family_id": int(family_id) if family_id else None,
+        "child_id": int(child_id) if child_id else None,
+        "report_id": int(report_id) if report_id else None,
+        "focus": focus,
+        "kb_context": None,
+        "knowledge_results": [],
+        "answer": None,
+        "tasks": [],
+        "sources": [],
+        "messages": None,
+    }
+    config = {
+        "configurable": {"thread_id": thread_id},
+    }
+    result = await graph.ainvoke(initial_state, config)
+    answer = result.get("answer") or ""
+
+    # 从回答中提取 TASK 标记
+    tasks = result.get("tasks") or []
+    sources = result.get("sources") or []
+    metadata = {"tasks": tasks, "sources": sources}
+
+    return DifyResponse(
+        id=f"butler-{uuid.uuid4().hex[:24]}",
+        created=_now_ts(),
+        model="langgraph-health-butler",
+        choices=[
+            DifyChoice(
+                index=0,
+                message={"role": "assistant", "content": answer},
+                finish_reason="stop",
+            )
+        ],
+        usage=DifyUsage(
+            prompt_tokens=len(query.split()),
+            completion_tokens=len(answer.split()),
+            total_tokens=len(query.split()) + len(answer.split()),
+        ),
+        metadata=metadata,
+    )
+
+
+def _parse_normal_range(ref_range: str) -> tuple[float | None, float | None]:
+    """解析正常范围字符串,返回 (下限, 上限),如 '30-100' → (30, 100), '<5' → (None, 5)"""
+    if not ref_range:
+        return None, None
+    ref_range = ref_range.strip()
+    m = re.match(r'([<>]=?)\s*([\d.]+)', ref_range)
+    if m:
+        op, val = m.group(1), float(m.group(2))
+        if op.startswith('>'):
+            return (val, None)
+        else:
+            return (None, val)
+    m = re.match(r'([\d.]+)\s*[-~]\s*([\d.]+)', ref_range)
+    if m:
+        return (float(m.group(1)), float(m.group(2)))
+    return None, None
+
+
+def _is_abnormal(status: str, value: float | None, low: float | None, high: float | None) -> bool:
+    """判断指标是否异常:优先用 status 字段,否则用数值与范围比较"""
+    if status and status not in ("正常", "正常范围", "未检出", ""):
+        return True
+    if value is not None and low is not None and high is not None:
+        return value < low or value > high
+    return False
+
+
+def _try_parse_value(raw: str) -> float | None:
+    if not raw:
+        return None
+    raw = raw.strip().replace(",", "").replace(" ", "")
+    try:
+        return float(raw)
+    except ValueError:
+        return None
+
+
+async def _search_knowledge(retriever: RagRetriever, query: str, k: int = 3) -> list[dict]:
+    """从知识库检索相关内容"""
+    try:
+        return await retriever.retrieve(query, k=k)
+    except Exception as e:
+        logger.warning("知识库检索失败: %s", e)
+        return []
+
+
+@router.post("/health/coach/generate")
+async def health_coach_generate(req: HealthCoachGenerateRequest):
+    """健康方案生成 — 选人→拉指标→查知识库→LLM"""
+    goal = req.goal or "改善健康状况"
+    member_ids_str = req.member_ids or ""
+    dimensions = req.dimensions or ""
+    member_ids = [m.strip() for m in member_ids_str.split(",") if m.strip()]
+
+    java = JavaClient()
+    retriever = RagRetriever(collection_name="cfc_knowledge")
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+
+    # ====== 1. 获取家庭成员信息 ======
+    members_info = []
+    if member_ids:
+        # 从 context 获取家庭信息
+        for uid_str in member_ids:
+            uid = int(uid_str)
+            ctx = await java.get_family_context(uid, "child_info")
+            children = ctx.get("children", []) if isinstance(ctx, dict) else []
+            for child in children:
+                child_id = str(child.get("用户ID", ""))
+                if child_id in member_ids:
+                    members_info.append({
+                        "id": child_id,
+                        "name": child.get("姓名", f"成员{child_id}"),
+                        "age": child.get("年龄", "未知"),
+                        "energy": child.get("能量", 0),
+                    })
+                    break
+            # 如果 context 没找到,用基本信息兜底
+            if not any(m["id"] == uid_str for m in members_info):
+                members_info.append({"id": uid_str, "name": f"成员{uid_str}", "age": "未知", "energy": 0})
+    else:
+        members_info.append({"id": "0", "name": "用户", "age": "未知", "energy": 0})
+
+    # ====== 2. 获取每个成员的指标数据 ======
+    all_indicators = []
+    for member in members_info:
+        uid = int(member["id"])
+        reports = await java.get_member_reports(uid)
+        if not reports:
+            logger.info("成员 %s 无健康报告", member["id"])
+            continue
+        latest = max(reports, key=lambda r: r.get("reportDate", ""))
+        report_id = latest.get("id")
+        member["latest_report_id"] = report_id
+        member["report_date"] = latest.get("reportDate", "")
+        member["overall_score"] = latest.get("overallScore", "未知")
+
+        indicators = await java.get_report_indicators(report_id)
+        for ind in indicators:
+            ind["_member_id"] = member["id"]
+            ind["_member_name"] = member["name"]
+            all_indicators.append(ind)
+
+    # ====== 3. 获取指标定义+正常范围 ======
+    known_indicators = {}
+    for ind in all_indicators:
+        name = ind.get("indicatorName", "").strip()
+        if not name or name in known_indicators:
+            continue
+        kb = await java.query_health_knowledge("indicator", name)
+        if not kb:
+            kb = await java.query_health_knowledge("bacteria", name)
+        if not kb:
+            kb = await java.query_health_knowledge("nutrient", name)
+        if kb:
+            known_indicators[name] = kb
+
+    # ====== 4. 识别异常指标 ======
+    abnormal_list = []
+    normal_list = []
+    for ind in all_indicators:
+        name = ind.get("indicatorName", "")
+        raw_val = ind.get("indicatorValue", "")
+        status = ind.get("status", "")
+        unit = ind.get("unit", "")
+        ref_range = ind.get("refRange", "")
+
+        # 优先用知识库中的正常范围
+        kb = known_indicators.get(name)
+        if kb and kb.get("normalRange"):
+            ref_range = kb.get("normalRange", ref_range)
+
+        low, high = _parse_normal_range(ref_range)
+        value = _try_parse_value(raw_val)
+        is_abnormal = _is_abnormal(status, value, low, high)
+
+        entry = {
+            "member": ind.get("_member_name", ""),
+            "indicator": name,
+            "value": raw_val,
+            "unit": unit,
+            "ref_range": ref_range,
+            "status": status,
+            "is_abnormal": is_abnormal,
+            "description": kb.get("description", "") if kb else "",
+            "suggestion": kb.get("suggestion", "") if kb else "",
+        }
+        if is_abnormal:
+            abnormal_list.append(entry)
+        else:
+            normal_list.append(entry)
+
+    # ====== 5. 检索知识库 ======
+    kb_results = []
+
+    # 5a. 异常指标检索
+    abnormal_queries = set()
+    for ind in abnormal_list:
+        abnormal_queries.add(ind["indicator"])
+    for q in list(abnormal_queries)[:5]:
+        results = await _search_knowledge(retriever, f"{q} 改善建议", k=3)
+        kb_results.extend(results)
+
+    # 5b. 用户需求检索
+    goal_results = await _search_knowledge(retriever, goal, k=5)
+    kb_results.extend(goal_results)
+
+    # 5c. 维度检索
+    if dimensions:
+        dim_results = await _search_knowledge(retriever, dimensions, k=3)
+        kb_results.extend(dim_results)
+
+    # 去重
+    seen_content = set()
+    deduped_kb = []
+    for r in kb_results:
+        h = r.get("content", "")[:100]
+        if h not in seen_content:
+            seen_content.add(h)
+            deduped_kb.append(r)
+
+    # ====== 6. 组装结构化 Prompt ======
+    prompt_parts = []
+
+    # 系统提示
+    prompt_parts.append(await get_prompt("health_plan_text") or TEXT_PLAN_SYSTEM_PROMPT)
+
+    # 目标与维度
+    prompt_parts.append(f"\n## 用户目标\n{goal}")
+    if dimensions:
+        prompt_parts.append(f"\n## 重点关注维度\n{dimensions}")
+
+    # 成员信息
+    prompt_parts.append("\n## 家庭成员")
+    for m in members_info:
+        scores = f"健康评分: {m.get('overall_score', '未知')}" if m.get('overall_score') else ""
+        report = f"最近报告: {m.get('report_date', '无')}" if m.get('report_date') else ""
+        prompt_parts.append(f"- {m['name']} (年龄: {m['age']}) {scores} {report}")
+
+    # 异常指标
+    if abnormal_list:
+        prompt_parts.append("\n## 异常指标")
+        for ind in abnormal_list:
+            parts = [f"- {ind['member']} - {ind['indicator']}: {ind['value']}{ind['unit']} (参考范围: {ind['ref_range']})"]
+            if ind['description']:
+                parts.append(f"  说明: {ind['description']}")
+            if ind['suggestion']:
+                parts.append(f"  建议: {ind['suggestion']}")
+            prompt_parts.append("\n".join(parts))
+
+    # 正常指标
+    if normal_list:
+        prompt_parts.append("\n## 正常指标(参考)")
+        normal_summary = [f"- {ind['indicator']}: {ind['value']}{ind['unit']} (正常)" for ind in normal_list[:10]]
+        prompt_parts.extend(normal_summary)
+
+    # 知识库参考
+    if deduped_kb:
+        prompt_parts.append("\n## 知识库参考(可引用)")
+        for r in deduped_kb[:8]:
+            title = r.get("metadata", {}).get("title", "")
+            content = r.get("content", "")[:300]
+            prompt_parts.append(f"---\n{title}\n{content}")
+
+    full_prompt = "\n".join(prompt_parts)
+
+    # ====== 7. 调用 LLM ======
+    request_template = await get_prompt("health_plan_text_request") or "请基于以上数据,生成一份针对{goal}的健康改善方案。"
+    try:
+        request_text = request_template.format(goal=goal)
+    except (KeyError, IndexError, ValueError):
+        logger.warning("Java 配置的 health_plan_text_request 模板缺少占位符,回退本地模板")
+        request_text = "请基于以上数据,生成一份针对{goal}的健康改善方案。".format(goal=goal)
+    messages = [
+        SystemMessage(content=full_prompt),
+        HumanMessage(content=request_text),
+    ]
+    response = await llm.ainvoke(messages)
+    answer = response.content
+
+    return answer
+
+
+# ===== 健康方案生成(结构化 JSON)=====
+
+class HealthPlanRequest(BaseModel):
+    # 兼容 camelCase(Java 侧历史写法)与 snake_case(本服务规范)两种入参键名
+    model_config = ConfigDict(populate_by_name=True)
+    member_ids: Optional[str] = Field(default=None, validation_alias=AliasChoices("member_ids", "memberIds"))
+    dimensions: Optional[str] = None
+    goal: str = ""
+    family_id: Optional[int] = Field(default=None, validation_alias=AliasChoices("family_id", "familyId"))
+    # HL-03/R3:用户对不确定点的对话补充回答(首次为空 dict,二次生成携带答案)
+    follow_up_answers: Optional[dict] = Field(default=None, validation_alias=AliasChoices("follow_up_answers", "followUpAnswers"))
+
+
+class HealthPlanRegenerateRequest(BaseModel):
+    model_config = ConfigDict(populate_by_name=True)
+    section: str  # nutrition | diet | exercise
+    feedback: str = ""
+    existing_section_content: str = ""
+    member_ids: Optional[str] = Field(default=None, validation_alias=AliasChoices("member_ids", "memberIds"))
+    dimensions: Optional[str] = None
+    goal: str = ""
+    family_id: Optional[int] = Field(default=None, validation_alias=AliasChoices("family_id", "familyId"))
+
+
+class HealthPlanAdjustRequest(BaseModel):
+    """对话式调整方案 request(HL-04/R4):自然语言调整意图 → 调整后板块内容"""
+    model_config = ConfigDict(populate_by_name=True)
+    section: str  # nutrition | diet | exercise
+    intent: str   # 自然语言调整意图,如「睡眠建议改温和一点」
+    existing_section_content: str = ""  # 当前板块完整内容(含多成员个性块)
+    member_ids: Optional[str] = Field(default=None, validation_alias=AliasChoices("member_ids", "memberIds"))
+    dimensions: Optional[str] = None
+    goal: str = ""
+    family_id: Optional[int] = Field(default=None, validation_alias=AliasChoices("family_id", "familyId"))
+
+
+TEXT_PLAN_SYSTEM_PROMPT = """你是一个专业的家庭健康方案生成器。请根据用户提供的健康数据,生成一份结构化的健康改善方案。
+
+输出格式要求:
+## 方案概述
+[简要说明方案的总体目标和适用对象]
+
+## 成员健康概况
+[每个成员的关键指标摘要]
+
+## 需要关注的异常指标
+[列出异常指标及对应的知识库建议]
+
+## 改善方案
+### 1. 饮食调整
+[具体、可执行的饮食建议]
+
+### 2. 生活习惯
+[具体、可执行的生活习惯建议]
+
+### 3. 补充建议
+[如需补充营养素或益生菌,给出具体建议]
+
+### 4. 跟踪建议
+[建议定期复查的指标和频率]
+
+## 注意事项
+[禁忌、提醒等]
+
+请基于实际数据给出建议,不要编造科学依据。引用知识库内容时标注来源。"""
+
+PLAN_SYSTEM_PROMPT = """你是一个专业的家庭健康方案规划师。根据用户提供的健康数据和目标,生成结构化的健康改善方案。
+
+## 输出格式(必须输出合法 JSON,不要有其他内容)
+
+{
+  "overview": "总体概述(100字以内,说明方案目标和核心策略)",
+  "sections": [
+    {
+      "key": "nutrition",
+      "title": "营养补充建议",
+      "content": "Markdown 格式的详细内容",
+      "items": [
+        {"name": "产品名", "dosage": "用量", "timing": "服用时间", "reason": "推荐理由"}
+      ],
+      "tasks": [
+        {
+          "action_type": "buy",
+          "title": "购买维生素D3补充剂",
+          "dimension": "wealth",
+          "frequency": "once",
+          "notes": "每日一粒,随餐服用"
+        }
+      ]
+    },
+    {
+      "key": "diet",
+      "title": "饮食建议",
+      "content": "Markdown 格式的餐饮建议",
+      "items": [{"meal": "餐型", "food": "食物建议", "notes": "注意事项"}],
+      "tasks": [
+        {
+          "action_type": "diet",
+          "title": "早餐增加高蛋白与膳食纤维",
+          "dimension": "body",
+          "frequency": "daily",
+          "notes": ""
+        }
+      ]
+    },
+    {
+      "key": "exercise",
+      "title": "运动计划",
+      "content": "Markdown 格式的运动建议",
+      "items": [{"type": "运动类型", "duration": "时长", "frequency": "频率", "notes": "注意事项"}],
+      "tasks": [
+        {
+          "action_type": "exercise",
+          "title": "每周3次有氧运动,每次30分钟",
+          "dimension": "body",
+          "frequency": "daily",
+          "notes": ""
+        }
+      ]
+    }
+  ],
+  "abnormal_indicators": [
+    {"member": "姓名", "indicator": "指标名", "value": "值", "unit": "单位", "suggestion": "建议"}
+  ]
+}
+
+## tasks 字段约定
+- 每个 section 的 `tasks` 是该 section 中"可执行的行动项"列表,与 `content`(人类可读 Markdown)分离。
+- `action_type` 取值仅限:`buy`(购买/补充产品)、`read`(阅读)、`exercise`(运动)、`checkin`(打卡/记录)、`diet`(饮食)、`activity`(活动/社交)。
+- `dimension` 取值仅限五维:`body`/`mind`/`wisdom`/`action`/`wealth`。
+- `frequency`:`once`=一次性任务;`daily`=每日重复任务。
+- `title` 是最终写入任务系统的标题,必须是**具体可执行的动作**,不要写纯原理/机制描述。
+- 若某 section 没有可执行的行动项,`tasks` 输出空数组 `[]`。
+
+## 原则
+1. 基于实际数据给出建议,不编造
+2. 引用知识库内容时标注来源
+3. 建议要具体可执行,避免空泛
+4. 营养补充部分要具体到产品类型和用量
+5. 严重健康问题建议咨询医生
+6. 当问卷中某项关键信息缺失或不确定(如抗生素用药史、排便性状、过敏表现、饮食结构不明确)时,应在方案末尾明确提示用户:「为了获得更精准的饮食建议,建议您进行肠道菌群检测(GI Navigator 或其他权威检测),以获取确切的菌群组成数据」。
+
+## 画像数据使用指南
+如果提供了用户的画像数据(五维评分、身体指标、心理指标等),请结合这些真实数据给出更有针对性的建议。特别关注异常指标(如睡眠不足、压力偏高、运动频率低等),在方案中明确说明这些指标的现状和改善方向。
+"""
+
+REGENERATE_SECTION_SYSTEM_PROMPT = """你是一个家庭健康方案规划师。根据用户反馈重新生成指定部分内容。
+
+## 输出格式(必须输出合法 JSON,不要有其他内容)
+{
+  "content": "重新生成的 Markdown 内容",
+  "tasks": [
+    {
+      "action_type": "buy|read|exercise|checkin|diet|activity",
+      "title": "可执行任务标题",
+      "dimension": "body|mind|wisdom|action|wealth",
+      "frequency": "once|daily",
+      "notes": "补充说明"
+    }
+  ]
+}
+
+## tasks 约定
+- action_type 取值:buy/read/exercise/checkin/diet/activity
+- dimension 取值:body/mind/wisdom/action/wealth
+- frequency:once=一次性;daily=每日重复
+- 无行动项时 tasks 输出 []
+
+## 原则
+- 保持与原格式一致
+- 结合用户反馈进行修改
+- 建议要具体可执行"""
+
+
+ADJUST_SECTION_SYSTEM_PROMPT = """你是一个家庭健康方案规划师。用户会用自然语言对方案的某个板块提出调整意图,请在「当前内容」基础上做针对性修改,而不是整段重写。
+
+## 调整原则
+- 只修改用户调整意图所指向的部分;与意图无关的建议、已有排版与格式一律保持不变
+- 保持原 Markdown 结构、标题层级与措辞风格
+- 若「当前内容」包含「### 成员 X」等成员个性块,除非调整意图明确指向该成员,否则这些块必须原样保留
+- 建议要具体、可执行,不泛泛而谈;调整后仍针对该板块主题(营养补充/饮食/运动)输出
+
+## 输出格式(必须输出合法 JSON,不要有其他内容)
+{
+  "content": "调整后的板块内容(Markdown)",
+  "tasks": [
+    {
+      "action_type": "buy|read|exercise|checkin|diet|activity",
+      "title": "可执行任务标题",
+      "dimension": "body|mind|wisdom|action|wealth",
+      "frequency": "once|daily",
+      "notes": "补充说明"
+    }
+  ]
+}
+
+## tasks 约定
+- action_type 取值:buy/read/exercise/checkin/diet/activity
+- dimension 取值:body/mind/wisdom/action/wealth
+- frequency:once=一次性;daily=每日重复
+- 调整意图不涉及新行动项时,tasks 必须输出 []"""
+
+
+def _format_diet_preferences(dp: dict) -> str:
+    if not dp:
+        return ""
+    parts = []
+    def _list(v):
+        if not v:
+            return ""
+        if isinstance(v, list):
+            return ", ".join(str(x) for x in v)
+        try:
+            parsed = json.loads(v)
+            if isinstance(parsed, list):
+                return ", ".join(str(x) for x in parsed)
+        except Exception:
+            pass
+        return str(v)
+    if dp.get("allergies"):
+        parts.append(f"过敏原:{_list(dp['allergies'])}")
+    if dp.get("absoluteAvoid"):
+        parts.append(f"忌口:{_list(dp['absoluteAvoid'])}")
+    if dp.get("mustEat"):
+        parts.append(f"必吃:{_list(dp['mustEat'])}")
+    if dp.get("religiousDiet") and dp["religiousDiet"] not in ("none", None, ""):
+        parts.append(f"宗教饮食:{dp['religiousDiet']}")
+    if dp.get("spiceLevel"):
+        parts.append(f"辣度:{dp['spiceLevel']}")
+    if dp.get("noPreference"):
+        parts.append("无特殊饮食偏好")
+    if dp.get("dietStructure"):
+        try:
+            ds = json.loads(dp["dietStructure"])
+            if isinstance(ds, dict):
+                if ds.get("vegetableFruit"):
+                    parts.append(f"每日蔬果量:{ds['vegetableFruit']}")
+                if ds.get("dairy"):
+                    parts.append(f"乳制品:{ds['dairy']}")
+                if ds.get("sugaryDrinks"):
+                    parts.append(f"含糖饮料:{ds['sugaryDrinks']}")
+        except Exception:
+            parts.append(f"饮食结构:{dp['dietStructure']}")
+    return "; ".join(parts)
+
+
+def _format_health_status(hs: dict) -> str:
+    if not hs:
+        return ""
+    def _arr(v):
+        if not v:
+            return ""
+        if isinstance(v, list):
+            return ", ".join(str(x.get("name", x)) if isinstance(x, dict) else str(x) for x in v)
+        try:
+            parsed = json.loads(v)
+            if isinstance(parsed, list):
+                return ", ".join(str(x.get("name", x)) if isinstance(x, dict) else str(x) for x in parsed)
+        except Exception:
+            pass
+        return v
+    out = []
+    if hs.get("heightCm"):
+        out.append(f"身高{hs['heightCm']}cm")
+    if hs.get("weightKg"):
+        out.append(f"体重{hs['weightKg']}kg")
+    if hs.get("bloodPressure"):
+        out.append(f"血压{hs['bloodPressure']}")
+    if hs.get("bloodGlucose"):
+        out.append(f"空腹血糖{hs['bloodGlucose']}mmol/L")
+    lipids = _arr(hs.get("bloodLipids"))
+    if lipids:
+        out.append(f"血脂:{lipids}")
+    diseases = _arr(hs.get("diseaseHistory"))
+    if diseases:
+        out.append(f"疾病史:{diseases}")
+    meds = _arr(hs.get("medications"))
+    if meds:
+        out.append(f"用药:{meds}")
+    if hs.get("notes"):
+        out.append(f"备注:{hs['notes']}")
+    # 生活方式与肠道健康(心情/睡眠/排便/抗生素/过敏表现)
+    if hs.get("lifestyle"):
+        try:
+            ls = json.loads(hs["lifestyle"])
+            parts = []
+            if isinstance(ls, dict):
+                if ls.get("mood"):
+                    parts.append(f"心情状态:{ls['mood']}")
+                if ls.get("sleepDuration"):
+                    parts.append(f"睡眠时长:{ls['sleepDuration']}")
+                if ls.get("bedtime"):
+                    parts.append(f"入睡时间:{ls['bedtime']}")
+                if ls.get("bowelFrequency"):
+                    parts.append(f"排便频率:{ls['bowelFrequency']}")
+                if ls.get("bowelForm"):
+                    parts.append(f"粪便性状:{ls['bowelForm']}")
+                if ls.get("antibioticHistory"):
+                    parts.append(f"近2年抗生素用药史:{ls['antibioticHistory']}")
+                if ls.get("allergySymptoms") and ls["allergySymptoms"]:
+                    sym = ", ".join(ls["allergySymptoms"]) if isinstance(ls["allergySymptoms"], list) else str(ls["allergySymptoms"])
+                    parts.append(f"过敏表现:{sym}")
+                # 按性别/年龄动态采集的专属项
+                if ls.get("menstrualCycle"):
+                    parts.append(f"月经周期:{ls['menstrualCycle']}")
+                if ls.get("specialPeriod"):
+                    parts.append(f"特殊时期:{ls['specialPeriod']}")
+                if ls.get("growthDevelopment"):
+                    parts.append(f"生长发育:{ls['growthDevelopment']}")
+                if ls.get("pickyEating"):
+                    parts.append(f"挑食情况:{ls['pickyEating']}")
+                if ls.get("osteoporosisRisk"):
+                    parts.append(f"骨质疏松风险:{ls['osteoporosisRisk']}")
+                if ls.get("fallRisk"):
+                    parts.append(f"跌倒风险:{ls['fallRisk']}")
+                if ls.get("screenTime"):
+                    parts.append(f"屏幕时间:{ls['screenTime']}")
+                if ls.get("teenMood"):
+                    parts.append(f"情绪状态:{ls['teenMood']}")
+            if parts:
+                out.append("生活方式:" + "; ".join(parts))
+        except Exception:
+            out.append(f"生活方式:{hs['lifestyle']}")
+    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()]
+
+    # 1. 家庭成员信息
+    members_info = []
+    for uid_str in member_ids:
+        ctx = await java.get_family_context(int(uid_str), "child_info")
+        children = ctx.get("children", []) if isinstance(ctx, dict) else []
+        for child in children:
+            cid = str(child.get("用户ID", ""))
+            if cid == uid_str:
+                members_info.append({
+                    "id": cid,
+                    "name": child.get("姓名", f"成员{cid}"),
+                    "age": child.get("年龄", "未知"),
+                })
+                break
+        if not any(m["id"] == uid_str for m in members_info):
+            members_info.append({"id": uid_str, "name": f"成员{uid_str}", "age": "未知"})
+
+    # 2. 健康指标
+    all_indicators = []
+    for member in members_info:
+        reports = await java.get_member_reports(int(member["id"]))
+        # HL-03/R3:记录报告类型,供不确定点检测(如缺少菌群报告)
+        member["report_types"] = [str(r.get("reportType", "")) for r in reports] if reports else []
+        member["has_gut_flora"] = any(t == "gut_flora" for t in member["report_types"])
+        if not reports:
+            continue
+        latest = max(reports, key=lambda r: r.get("reportDate", ""))
+        indicators = await java.get_report_indicators(latest.get("id"))
+        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:
+        try:
+            member["health_status"] = await java.get_member_health_status(int(member["id"]))
+        except Exception:
+            member["health_status"] = {}
+        try:
+            member["diet_preferences"] = await java.get_member_diet_preferences(int(member["id"]))
+        except Exception:
+            member["diet_preferences"] = {}
+
+    # 3. 知识库
+    kb_results = []
+    queries = set()
+    for ind in all_indicators:
+        queries.add(ind.get("indicatorName", ""))
+    queries.add(goal)
+    if dimensions:
+        queries.add(dimensions)
+    for q in list(queries)[:8]:
+        if q:
+            results = await retriever.retrieve(q, k=3)
+            kb_results.extend(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:
+    """HL-03/R3:检测生成方案时的不确定点(问卷未涉及但需了解的特殊问题)。
+
+    首次生成(follow_up_answers 为空)时按数据缺失检测;用户已回答(follow_up_answers 非空)时
+    返回空列表,避免重复追问。每个不确定点形如 {id, question, hint}。
+    """
+    if follow_up_answers:
+        # 已回答 → 二次生成不再追问
+        return []
+    questions: list = []
+    if not members_info:
+        return questions
+
+    # 缺少肠道菌群检测数据
+    has_gut = any(m.get("has_gut_flora") for m in members_info)
+    if not has_gut:
+        questions.append({
+            "id": "gut_flora",
+            "question": "是否做过肠道菌群检测?如果做过,报告中明显的异常是什么?(如某菌属偏低/偏高、菌群多样性不足)",
+            "hint": "问卷外补充:用于精准定位肠道菌群维度",
+        })
+
+    # 缺少健康自检(health_status)信息
+    has_health_status = any(
+        isinstance(m.get("health_status"), dict) and m.get("health_status") for m in members_info
+    )
+    if not has_health_status:
+        questions.append({
+            "id": "health_status",
+            "question": "最近一次体检/健康评估中,有哪些指标明显异常?(如血脂、血糖、维生素缺乏等)",
+            "hint": "问卷外补充:帮助定制饮食与营养建议",
+        })
+    return questions
+
+
+def _format_follow_up_answers(follow_up_answers: Optional[dict]) -> str:
+    """将用户对话补充回答格式化为 prompt 片段(空则返回空串)。"""
+    if not follow_up_answers:
+        return ""
+    lines = ["", "## 用户补充回答(对话式特殊问题)"]
+    for key, val in follow_up_answers.items():
+        lines.append(f"- {key}: {val}")
+    return "\n".join(lines)
+
+
+# 从 LLM 原始输出中提取 tasks 的正则兜底:在 content 文本里找形如
+# "1. 动作(动词/名词)..." 的行。以可识别的动作词开头视为潜在任务。
+_TASK_FALLBACK_RE = re.compile(r"^\s*(?:\d+[\.、)]|\-\s*)\s*"
+                               r"(?:(?:购买|购置|阅读|看|运动|锻炼|跑步|散步|打卡|记录|饮食|吃|少|多|活动|参加|亲子).*)$")
+
+
+def _parse_plan_response(answer: str) -> dict:
+    """解析 LLM 原始输出为 HealthPlanResponse;非法 JSON 或校验失败时用正则兜底提取 tasks。
+
+    返回 dict:{"success": bool, "data": {...}, "error": str|None}
+    """
+    start = answer.find("{")
+    end = answer.rfind("}") + 1
+    if start >= 0 and end > start:
+        try:
+            parsed = json.loads(answer[start:end])
+            resp = HealthPlanResponse.model_validate(parsed)
+            return {"success": True, "data": resp.model_dump(), "error": None}
+        except Exception as e:
+            # 校验失败:尝试正则兜底
+            fallback = _fallback_extract_tasks(parsed if isinstance(parsed, dict) else {})
+            if fallback is not None:
+                return {"success": True, "data": fallback, "error": str(e)}
+            return {"success": False, "data": {"raw": answer, "overview": answer[:200]},
+                    "error": str(e)}
+    return {"success": False, "data": {"raw": answer, "overview": answer[:200]},
+            "error": "no JSON found"}
+
+
+def _fallback_extract_tasks(parsed: dict) -> Optional[dict]:
+    """当 LLM 输出缺 tasks 或校验失败时,从各 section.content 用正则提取任务并回填。
+    任一 section 无 tasks 才触发;全部已含 tasks 则返回 None(表示无需兜底)。"""
+    if not isinstance(parsed, dict):
+        return None
+    sections = parsed.get("sections")
+    if not isinstance(sections, list) or not sections:
+        return None
+    changed = False
+    for sec in sections:
+        if not isinstance(sec, dict):
+            continue
+        tasks = sec.get("tasks")
+        if isinstance(tasks, list) and tasks:
+            # 检查 tasks 是否全部有效;如有无效项则视为缺失,触发 fallback
+            try:
+                for t in tasks:
+                    PlanTask.model_validate(t)
+                continue  # 全部有效,跳过
+            except Exception:
+                pass  # 有无效项,继续执行 fallback
+        content = sec.get("content", "")
+        extracted = []
+        for raw in content.split("\n"):
+            line = raw.strip()
+            if not line:
+                continue
+            m = _TASK_FALLBACK_RE.match(line)
+            if not m:
+                continue
+            # 去掉行首编号/项目符号
+            title = re.sub(r"^\s*(?:\d+[\.、)]|\-\s*)\s*", "", line).strip()
+            if not title:
+                continue
+            action = _classify_action(title)
+            if action is None:
+                continue
+            extracted.append({
+                "action_type": action["action_type"],
+                "title": title,
+                "dimension": action["dimension"],
+                "frequency": action["frequency"],
+                "notes": "",
+            })
+        if extracted:
+            sec["tasks"] = extracted
+            changed = True
+    if changed:
+        return parsed
+    return None
+
+
+def _classify_action(title: str) -> Optional[dict]:
+    """按动作词分类,映射到 action_type + 五维维度 + 频率(与 Java classifyTaskLine 对齐)。"""
+    if re.search(r"购买|购置|采购|下单|买入|囤|选购", title):
+        return {"action_type": "buy", "dimension": "wealth", "frequency": "once"}
+    if re.search(r"阅读|看|读书", title):
+        return {"action_type": "read", "dimension": "wisdom", "frequency": "daily"}
+    if re.search(r"运动|锻炼|跑步|散步|健身|瑜伽|拉伸", title):
+        return {"action_type": "exercise", "dimension": "body", "frequency": "daily"}
+    if re.search(r"打卡|记录|复盘|记", title):
+        return {"action_type": "checkin", "dimension": "mind", "frequency": "daily"}
+    if re.search(r"饮食|吃|少|多|餐|营养|水", title):
+        return {"action_type": "diet", "dimension": "body", "frequency": "daily"}
+    if re.search(r"活动|参加|亲子|社交|户外|游戏", title):
+        return {"action_type": "activity", "dimension": "action", "frequency": "daily"}
+    return None
+
+
+MULTI_MEMBER_SYNTHESIS_PROMPT = """你是一个家庭健康方案规划师。以下是一个家庭中 N 位成员的独立健康方案(每位成员已由 LLM 单独生成)。请分析这些方案,找出共性部分与个性部分,输出结构化 JSON。
+
+## 输出格式(必须输出合法 JSON,不要有其他内容)
+
+{
+  "common": {
+    "overview": "所有成员共性的总体概述(100 字以内,说明方案目标和核心策略)",
+    "sections": [
+      {
+        "key": "nutrition|diet|exercise",
+        "title": "营养补充建议",
+        "content": "Markdown 格式的详细内容",
+        "items": [],
+        "tasks": [
+          {
+            "action_type": "buy|read|exercise|checkin|diet|activity",
+            "title": "具体可执行动作(如:购买维生素D3补充剂)",
+            "dimension": "body|mind|wisdom|action|wealth",
+            "frequency": "once|daily",
+            "notes": "补充说明(可空)"
+          }
+        ]
+      }
+    ],
+    "abnormal_indicators": []
+  },
+  "individual": {
+    "<memberId>": {
+      "overview": "该成员独有的总体概述(如该成员无独有内容,写\"无\")",
+      "sections": [
+        {
+          "key": "nutrition|diet|exercise",
+          "title": "营养补充建议(个性化)",
+          "content": "Markdown 格式的详细内容",
+          "items": [],
+          "tasks": [
+            {
+              "action_type": "buy|read|exercise|checkin|diet|activity",
+              "title": "具体可执行动作",
+              "dimension": "body|mind|wisdom|action|wealth",
+              "frequency": "once|daily",
+              "notes": "补充说明(可空)"
+            }
+          ]
+        }
+      ],
+      "abnormal_indicators": [
+        {"member": "姓名", "indicator": "指标名", "value": "值", "unit": "单位", "suggestion": "建议"}
+      ]
+    }
+  }
+}
+
+## 规则
+1. **common**:出现在至少两个成员方案中的相似/重复内容。包括:共同适用的饮食大方向、共同的生活习惯、所有人都需要执行的锻炼/打卡等。**common 的 sections 应保留完整 tasks,因为这些任务会分配给每个成员各一份。**
+2. **individual.<memberId>**:只适用于该成员独有的内容,包括:针对该成员专属指标异常的建议、该成员特有的疾病史/过敏史、年龄相关的个性化建议等。该成员的个性 section 不能包含已放入 common 的内容(避免重复)。
+3. 如果某成员没有独有内容,其 individual 的 sections 为空数组 `[]`,overview 写"无",abnormal_indicators 为 `[]`。
+4. **abnormal_indicators**:多成员共有的异常指标放入 common;只属于某个成员的异常指标放入 individual 该成员的 abnormal_indicators。
+5. knowledge_sources 不输出。
+
+## 任务约定
+- `action_type` 取值仅限:`buy`(购买/补充产品)、`read`(阅读)、`exercise`(运动)、`checkin`(打卡/记录)、`diet`(饮食)、`activity`(活动/社交)。
+- `dimension` 取值仅限五维:`body`/`mind`/`wisdom`/`action`/`wealth`。
+- `frequency`:`once`=一次性任务;`daily`=每日重复任务。
+- `title` 必须是**具体可执行的动作**,不要写纯原理/机制描述。
+- 若某 section 没有可执行的行动项,`tasks` 输出空数组 `[]`。"""
+
+
+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}")
+    if dimensions:
+        parts.append(f"\n## 重点关注维度\n{dimensions}")
+    parts.append("\n## 成员信息")
+    profile = member.get("profile", {})
+    dims = profile.get("dimension_scores", {})
+    body = profile.get("body_metrics", {})
+    mind = profile.get("mind_metrics", {})
+    parts.append(f"- {member['name']} (id: {member['id']}, 年龄: {member['age']})")
+    hs_text = _format_health_status(member.get("health_status"))
+    if hs_text:
+        parts.append(f"  健康自检: {hs_text}")
+    dp_text = _format_diet_preferences(member.get("diet_preferences"))
+    if dp_text:
+        parts.append(f"  饮食偏好: {dp_text}")
+    if dims:
+        parts.append(f"  五维评分: 身{dims.get('body','?')} 智{dims.get('wisdom','?')} 心{dims.get('mind','?')} 行{dims.get('action','?')} 富{dims.get('wealth','?')}")
+    if body.get('sleep_dur_avg'):
+        parts.append(f"  平均睡眠: {body['sleep_dur_avg']}小时/天")
+    if mind.get('stress_avg'):
+        parts.append(f"  平均压力: {mind['stress_avg']}/10")
+    if body.get('exercise_count_week'):
+        parts.append(f"  周运动: {body['exercise_count_week']}次")
+    if member_indicators:
+        parts.append("\n## 该成员健康指标")
+        for ind in member_indicators[:15]:
+            status = ind.get("status", "")
+            if status in ("abnormal", "high", "low", "偏高", "偏低"):
+                parts.append(f"- 【异常】{ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')} (状态: {status})")
+            else:
+                parts.append(f"- {ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')}")
+    if kb_results:
+        parts.append("\n## 知识库参考")
+        for r in kb_results[:6]:
+            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,
+                                    kb_structured_context: dict | None = None) -> dict:
+    """为单个成员调用 LLM 生成独立方案;返回 HealthPlanResponse.model_dump() 结构,失败返回 {}。"""
+    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)
+        if result["success"]:
+            return result["data"]
+        logger.warning("成员 %s 方案生成解析失败: %s", member.get("name"), result.get("error"))
+        return {}
+    except Exception as e:
+        logger.error("成员 %s 方案生成失败: %s", member.get("name"), e)
+        return {}
+
+
+async def _synthesize_multi_member_plan(llm, members_info: list, individual_plans: dict, goal: str, dimensions: str,
+                                        follow_up_answers: Optional[dict] = None) -> dict:
+    """将 N 份单人方案交给 LLM 做交集合成,返回 MultiMemberPlanResponse.model_dump() 结构。
+
+    LLM 失败或输出不合法时,退化为纯程序拼接:common 各部分置空,individual 直接透传各成员方案。
+    follow_up_answers(HL-03/R3):用户对话补充回答,非空时并入合成 prompt 供 LLM 参考。
+    """
+    blocks = []
+    for m in members_info:
+        mid = str(m["id"])
+        plan = individual_plans.get(mid, {})
+        block_lines = [f"### 成员 {m['name']} (memberId: {mid})"]
+        if not plan:
+            block_lines.append("(无数据,individual 对应位置输出空 sections)")
+        else:
+            ov = plan.get("overview", "")
+            if ov:
+                block_lines.append(f"概述: {ov}")
+            for s in plan.get("sections", []):
+                skey = s.get("key", "")
+                stitle = s.get("title", "")
+                scontent = s.get("content", "")
+                sitems = s.get("items") or []
+                stasks = s.get("tasks") or []
+                block_lines.append(f"[{skey}] {stitle}")
+                block_lines.append(f"  content:\n{scontent}")
+                if sitems:
+                    block_lines.append(f"  items: {json.dumps(sitems, ensure_ascii=False)[:400]}")
+                if stasks:
+                    block_lines.append(f"  tasks: {json.dumps(stasks, ensure_ascii=False)[:400]}")
+            ai = plan.get("abnormal_indicators") or []
+            if ai:
+                block_lines.append(f"异常指标: {json.dumps(ai, ensure_ascii=False)[:300]}")
+        blocks.append("\n".join(block_lines))
+
+    prompt = MULTI_MEMBER_SYNTHESIS_PROMPT + "\n\n## 各成员独立方案(请按 memberId 归并,memberId 必须与下列标题中的 id 完全一致)\n\n"
+    prompt += "\n\n---\n\n".join(blocks)
+    # HL-03/R3:用户补充回答并入合成 prompt(首次为空串)
+    prompt += _format_follow_up_answers(follow_up_answers)
+    try:
+        response = await llm.ainvoke([SystemMessage(content=prompt)])
+        answer = response.content
+        start = answer.find("{")
+        end = answer.rfind("}") + 1
+        if start >= 0 and end > start:
+            parsed = json.loads(answer[start:end])
+            # 用 Pydantic 校验并规整结构
+            mmpr = MultiMemberPlanResponse.model_validate(parsed)
+            return mmpr.model_dump()
+        logger.warning("多人方案交集合成 LLM 输出无 JSON,退化为程序拼接")
+    except Exception as e:
+        logger.error("多人方案交集合成失败: %s,退化为程序拼接", e)
+
+    # 程序化兜底:common 置空,individual 直接透传各成员方案
+    individual = {}
+    for m in members_info:
+        mid = str(m["id"])
+        plan = individual_plans.get(mid, {})
+        if plan:
+            sections = []
+            for s in plan.get("sections", []):
+                try:
+                    sections.append(HealthPlanSection.model_validate(s))
+                except Exception:
+                    continue
+            individual[mid] = PlanPart(
+                overview=plan.get("overview", ""),
+                sections=sections,
+                abnormal_indicators=plan.get("abnormal_indicators", []),
+            )
+    return MultiMemberPlanResponse(common=PlanPart(overview=""), individual=individual).model_dump()
+
+
+@router.post("/health/plan/generate", response_model=dict)
+async def health_plan_generate(req: HealthPlanRequest):
+    """健康方案生成 — 返回结构化 JSON(总览+营养+饮食+运动)"""
+    goal = req.goal or "改善健康状况"
+    java = JavaClient()
+    retriever = RagRetriever(collection_name="cfc_knowledge")
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+
+    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:
+        try:
+            profile = await java.get_member_profile(int(member["id"]))
+            member["profile"] = profile
+        except Exception:
+            member["profile"] = {}
+
+    # HL-03/R3:检测不确定点(首次生成,二次生成已回答返回空)
+    follow_up_questions = _detect_follow_up_questions(members_info, req.follow_up_answers)
+
+    # === 多人方案:先每人单独生成,再 LLM 交集合成(共性/个性) ===
+    if len(members_info) > 1:
+        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 "", 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)
+        result["follow_up_questions"] = follow_up_questions
+        return {"success": True, "data": result, "parse_error": None}
+
+    # === 单人生成:保持原有 flat 结构(向后兼容) ===
+    # 构建 prompt
+    parts = [await get_prompt("health_plan") or PLAN_SYSTEM_PROMPT]
+    parts.append(f"\n## 用户目标\n{goal}")
+    if req.dimensions:
+        parts.append(f"\n## 重点关注维度\n{req.dimensions}")
+    parts.append("\n## 家庭成员")
+    for m in members_info:
+        profile = m.get("profile", {})
+        dims = profile.get("dimension_scores", {})
+        body = profile.get("body_metrics", {})
+        mind = profile.get("mind_metrics", {})
+        parts.append(f"- {m['name']} (年龄: {m['age']})")
+        hs_text = _format_health_status(m.get("health_status"))
+        if hs_text:
+            parts.append(f"  健康自检: {hs_text}")
+        dp_text = _format_diet_preferences(m.get("diet_preferences"))
+        if dp_text:
+            parts.append(f"  饮食偏好: {dp_text}")
+        if dims:
+            parts.append(f"  五维评分: 身{dims.get('body','?')} 智{dims.get('wisdom','?')} 心{dims.get('mind','?')} 行{dims.get('action','?')} 富{dims.get('wealth','?')}")
+        if body.get('sleep_dur_avg'):
+            parts.append(f"  平均睡眠: {body['sleep_dur_avg']}小时/天")
+        if mind.get('stress_avg'):
+            parts.append(f"  平均压力: {mind['stress_avg']}/10")
+        if body.get('exercise_count_week'):
+            parts.append(f"  周运动: {body['exercise_count_week']}次")
+
+    if all_indicators:
+        parts.append("\n## 健康指标摘要")
+        for ind in all_indicators[:15]:
+            status = ind.get("status", "")
+            if status in ("abnormal", "high", "low", "偏高", "偏低"):
+                parts.append(f"- 【异常】{ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')} (状态: {status})")
+            else:
+                parts.append(f"- {ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')} {ind.get('unit','')}")
+
+    if kb_results:
+        parts.append("\n## 知识库参考")
+        for r in kb_results[:6]:
+            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(首次为空串)
+    full_prompt += _format_follow_up_answers(req.follow_up_answers)
+
+    messages = [SystemMessage(content=full_prompt)]
+    try:
+        response = await llm.ainvoke(messages)
+        answer = response.content
+        result = _parse_plan_response(answer)
+        data = result["data"]
+        # HL-03/R3:不确定点随 data 返回(首次生成),前端对话式补充后带 followUpAnswers 二次生成
+        data["follow_up_questions"] = follow_up_questions
+        return {"success": True, "data": data, "parse_error": result["error"]}
+    except Exception as e:
+        logger.error("方案生成失败: %s", e)
+        return {"success": False, "error": str(e)}
+
+
+@router.post("/health/plan/regenerate-section", response_model=dict)
+async def health_plan_regenerate(req: HealthPlanRegenerateRequest):
+    """重新生成方案的某一个 section"""
+    java = JavaClient()
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+
+    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}"]
+    for m in members_info:
+        ctx_parts.append(f"- {m['name']} (年龄: {m['age']})")
+        hs_text = _format_health_status(m.get("health_status"))
+        if hs_text:
+            ctx_parts.append(f"  健康自检: {hs_text}")
+        dp_text = _format_diet_preferences(m.get("diet_preferences"))
+        if dp_text:
+            ctx_parts.append(f"  饮食偏好: {dp_text}")
+    for ind in all_indicators[:10]:
+        if ind.get("status") in ("abnormal", "high", "low", "偏高", "偏低"):
+            ctx_parts.append(f"- 【异常】{ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')}")
+
+    prompt = await get_prompt("health_plan_regenerate") or REGENERATE_SECTION_SYSTEM_PROMPT
+    prompt += f"\n\n## 当前 {req.section} 内容\n{req.existing_section_content[:500]}"
+    prompt += f"\n\n## 用户反馈\n{req.feedback}"
+    prompt += f"\n\n## 相关背景\n" + "\n".join(ctx_parts[:10])
+
+    try:
+        response = await llm.ainvoke([SystemMessage(content=prompt)])
+        answer = response.content
+        start = answer.find("{")
+        end = answer.rfind("}") + 1
+        content = answer
+        tasks = []
+        if start >= 0 and end > start:
+            try:
+                parsed = json.loads(answer[start:end])
+                content = parsed.get("content") or answer
+                raw_tasks = parsed.get("tasks") or []
+                # 用 PlanTask 校验,非法条目丢弃
+                for t in raw_tasks:
+                    try:
+                        pt = PlanTask.model_validate(t)
+                        tasks.append(pt.model_dump())
+                    except Exception:
+                        continue
+            except Exception as e:
+                logger.warning("解析重生成 section JSON 失败: %s", e)
+        return {"success": True, "content": content, "tasks": tasks}
+    except Exception as e:
+        logger.error("重新生成 section 失败: %s", e)
+        return {"success": False, "error": str(e)}
+
+
+@router.post("/health/plan/adjust", response_model=dict)
+async def health_plan_adjust(req: HealthPlanAdjustRequest):
+    """对话式调整方案板块(HL-04/R4):
+    输入自然语言调整意图(如「睡眠建议改温和一点」)→ 返回调整后的板块内容。
+    与 regenerate-section 的区别:只在当前内容基础上做局部微调,不整段重写。"""
+    java = JavaClient()
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+
+    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}"]
+    for m in members_info:
+        ctx_parts.append(f"- {m['name']} (年龄: {m['age']})")
+        hs_text = _format_health_status(m.get("health_status"))
+        if hs_text:
+            ctx_parts.append(f"  健康自检: {hs_text}")
+        dp_text = _format_diet_preferences(m.get("diet_preferences"))
+        if dp_text:
+            ctx_parts.append(f"  饮食偏好: {dp_text}")
+    for ind in all_indicators[:10]:
+        if ind.get("status") in ("abnormal", "high", "low", "偏高", "偏低"):
+            ctx_parts.append(f"- 【异常】{ind.get('_member_name','')} - {ind.get('indicatorName','')}: {ind.get('indicatorValue','')}")
+
+    prompt = await get_prompt("health_plan_adjust") or ADJUST_SECTION_SYSTEM_PROMPT
+    prompt += f"\n\n## 调整板块\n{req.section}"
+    prompt += f"\n\n## 当前内容\n{req.existing_section_content[:2000]}"
+    prompt += f"\n\n## 用户调整意图\n{req.intent}"
+    if ctx_parts:
+        prompt += "\n\n## 相关背景\n" + "\n".join(ctx_parts[:10])
+
+    try:
+        response = await llm.ainvoke([SystemMessage(content=prompt)])
+        answer = response.content
+        start = answer.find("{")
+        end = answer.rfind("}") + 1
+        content = answer
+        tasks = []
+        note = ""
+        if start >= 0 and end > start:
+            try:
+                parsed = json.loads(answer[start:end])
+                content = parsed.get("content") or answer
+                raw_tasks = parsed.get("tasks") or []
+                note = parsed.get("note") or ""
+                # 用 PlanTask 校验,非法条目丢弃
+                for t in raw_tasks:
+                    try:
+                        pt = PlanTask.model_validate(t)
+                        tasks.append(pt.model_dump())
+                    except Exception:
+                        continue
+            except Exception as e:
+                logger.warning("解析调整 section JSON 失败: %s", e)
+        return {"success": True, "content": content, "tasks": tasks, "note": note}
+    except Exception as e:
+        logger.error("对话式调整 section 失败: %s", e)
+        return {"success": False, "error": str(e)}
+
+
+@router.post("/nutrition/send", response_model=DifyResponse)
+async def nutrition_send(req: DifyChatRequest):
+    """AI 营养助手 — 基于健康报告的个性化营养建议"""
+    query = _extract_query(req)
+    if not query:
+        raise HTTPException(status_code=400, detail="query 为空")
+
+    graph = create_nutrition_graph()
+    initial_state = {
+        "query": query,
+        "user_id": int(req.user_id) if str(req.user_id).isdigit() else 0,
+        "child_id": int(req.inputs.get("child_id")) if req.inputs.get("child_id") else None,
+        "conversation_id": req.conversation_id or None,
+        "context": _to_langgraph_context(req),
+        "answer": None,
+        "sources": [],
+        "tasks": [],
+        "messages": None,
+    }
+    config = {
+        "configurable": {"thread_id": req.conversation_id or f"nutrition_{req.user_id}"},
+    }
+    result = await graph.ainvoke(initial_state, config)
+    answer = result.get("answer") or ""
+
+    sources = result.get("sources") or []
+    metadata = {}
+    if sources:
+        metadata["sources"] = [
+            {"title": s.get("name", ""), "type": s.get("type", "tool")}
+            for s in sources
+        ]
+
+    return DifyResponse(
+        id=f"nutrition-{uuid.uuid4().hex[:24]}",
+        created=_now_ts(),
+        model="langgraph-nutrition",
+        choices=[
+            DifyChoice(
+                index=0,
+                message={"role": "assistant", "content": answer},
+                finish_reason="stop",
+            )
+        ],
+        usage=DifyUsage(
+            prompt_tokens=len(query.split()),
+            completion_tokens=len(answer.split()),
+            total_tokens=len(query.split()) + len(answer.split()),
+        ),
+        metadata=metadata,
+    )

+ 50 - 0
cfc-langgraph/app/api/analyze.py

@@ -0,0 +1,50 @@
+from fastapi import APIRouter
+from pydantic import BaseModel
+from typing import Optional
+from app.graphs.analysis_graph import create_analysis_graph
+
+router = APIRouter(prefix="/api/v1", tags=["analyze"])
+
+_graph = None
+
+
+def get_graph():
+    global _graph
+    if _graph is None:
+        _graph = create_analysis_graph()
+    return _graph
+
+
+class AnalyzeRequest(BaseModel):
+    report_id: int
+    user_id: int
+    focus: Optional[str] = None
+
+
+class AnalyzeResponse(BaseModel):
+    analysis: str = ""
+    recommendations: list[str] = []
+    trace_id: str = ""
+
+
+@router.post("/analyze", response_model=AnalyzeResponse)
+async def analyze(req: AnalyzeRequest):
+    graph = get_graph()
+    import uuid
+    trace_id = str(uuid.uuid4())
+    # MemorySaver/AsyncSqliteSaver 均要求 config 提供 thread_id,缺省会抛
+    # "Checkpointer requires one or more of the following 'configurable' keys"
+    config = {
+        "configurable": {"thread_id": f"analyze_{req.user_id}_{trace_id}"},
+    }
+    result = await graph.ainvoke({
+        "report_id": req.report_id,
+        "user_id": req.user_id,
+        "focus": req.focus,
+        "report_data": None,
+        "survey_data": None,
+        "dimension_scores": None,
+        "analysis": None,
+        "recommendations": [],
+    }, config)
+    return AnalyzeResponse(analysis=result.get("analysis", ""), trace_id=trace_id)

+ 24 - 0
cfc-langgraph/app/api/article_quiz.py

@@ -0,0 +1,24 @@
+from fastapi import APIRouter
+from app.models.article_quiz import ArticleQuizRequest, ArticleQuizResponse
+from app.graphs.article_quiz_graph import ArticleQuizAgent
+import logging
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["article_quiz"])
+
+_agent = None
+
+
+def get_agent() -> ArticleQuizAgent:
+    global _agent
+    if _agent is None:
+        _agent = ArticleQuizAgent()
+    return _agent
+
+
+@router.post("/article/quiz/generate", response_model=ArticleQuizResponse)
+async def generate_article_quiz(req: ArticleQuizRequest):
+    agent = get_agent()
+    result = await agent.run(req.article_title, req.article_content, req.profile_summary)
+    return ArticleQuizResponse(questions=result.get("questions", []),
+                               fallback_used=result.get("fallback_used", True))

+ 48 - 0
cfc-langgraph/app/api/audio.py

@@ -0,0 +1,48 @@
+"""语音转写端点"""
+import os
+import uuid
+import logging
+from fastapi import APIRouter, UploadFile, File, HTTPException
+from pydantic import BaseModel
+from typing import Optional
+from app.audio.transcriber import transcribe_audio
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["audio"])
+
+MAX_FILE_SIZE = 5 * 1024 * 1024
+UPLOAD_DIR = "/tmp/stt_uploads"
+
+
+class TranscribeResponse(BaseModel):
+    code: int = 200
+    message: str = "ok"
+    data: Optional[dict] = None
+
+
+@router.post("/audio/transcribe", response_model=TranscribeResponse)
+async def transcribe(file: UploadFile = File(...)):
+    if not file.filename or not file.filename.lower().endswith((".mp3", ".wav", ".m4a", ".flac", ".ogg")):
+        raise HTTPException(status_code=400, detail="不支持的音频格式,仅支持 mp3/wav/m4a/flac/ogg")
+    content = await file.read()
+    if len(content) > MAX_FILE_SIZE:
+        raise HTTPException(status_code=413, detail="音频文件过大(最大 5MB)")
+    if len(content) < 1000:
+        raise HTTPException(status_code=400, detail="音频文件为空或过短")
+
+    os.makedirs(UPLOAD_DIR, exist_ok=True)
+    ext = file.filename.rsplit(".", 1)[-1]
+    tmp_path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.{ext}")
+    try:
+        with open(tmp_path, "wb") as f:
+            f.write(content)
+        result = transcribe_audio(tmp_path)
+        return TranscribeResponse(data=result)
+    except Exception as e:
+        logger.error("转写失败: %s", e, exc_info=True)
+        return TranscribeResponse(code=500, message="转写失败: " + str(e), data={})
+    finally:
+        try:
+            os.remove(tmp_path)
+        except OSError:
+            pass

+ 59 - 0
cfc-langgraph/app/api/chat.py

@@ -0,0 +1,59 @@
+import uuid
+from fastapi import APIRouter
+from app.models.chat import ChatRequest, ChatResponse, SourceInfo
+from app.graphs.chat_graph import create_chat_graph
+
+router = APIRouter(prefix="/api/v1", tags=["chat"])
+
+_graph = None
+
+
+def get_graph():
+    global _graph
+    if _graph is None:
+        _graph = create_chat_graph()
+    return _graph
+
+
+@router.post("/chat", response_model=ChatResponse)
+async def chat(req: ChatRequest):
+    """家庭聊天: 意图分类→上下文→LLM→记忆"""
+    trace_id = str(uuid.uuid4())
+    graph = get_graph()
+
+    initial_state = {
+        "query": req.query,
+        "user_id": req.user_id,
+        "conversation_id": req.conversation_id,
+        "child_id": req.context.child_id if req.context else None,
+        "intent": None,
+        "context": None,
+        "self_check_result": req.context.self_check_result if req.context and req.context.self_check_result else None,
+        "messages": None,
+        "answer": None,
+        "tasks": [],
+        "sources": [],
+    }
+
+    config = {
+        "configurable": {"thread_id": req.conversation_id or str(req.user_id)},
+    }
+
+    result = await graph.ainvoke(initial_state, config)
+
+    sources = []
+    for s in result.get("sources", []):
+        sources.append(SourceInfo(
+            type=s.get("type", "tool"),
+            title=s.get("name", ""),
+        ))
+
+    conv_id = req.conversation_id or f"conv_{req.user_id}_{__import__('time').time()}"
+
+    return ChatResponse(
+        answer=result.get("answer", ""),
+        conversation_id=conv_id,
+        sources=sources,
+        tasks=result.get("tasks", []),
+        trace_id=trace_id,
+    )

+ 8 - 0
cfc-langgraph/app/api/health.py

@@ -0,0 +1,8 @@
+from fastapi import APIRouter
+
+router = APIRouter(tags=["health"])
+
+
+@router.get("/health")
+async def health():
+    return {"status": "ok"}

+ 64 - 0
cfc-langgraph/app/api/indicator_classify.py

@@ -0,0 +1,64 @@
+from fastapi import APIRouter
+from pydantic import BaseModel
+from typing import Optional, List
+from app.llm.client import get_llm
+from langchain_core.messages import SystemMessage, HumanMessage
+import logging
+import json
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["indicator_classify"])
+_llm = None
+
+
+def get_llm_instance():
+    global _llm
+    if _llm is None:
+        _llm = get_llm()
+    return _llm
+
+
+class ClassifyRequest(BaseModel):
+    source_type: str
+    raw_name: str
+    candidates: Optional[List[str]] = None
+
+
+class ClassifyResponse(BaseModel):
+    code: int = 200
+    message: str = "ok"
+    data: dict = {}
+
+
+SYSTEM_PROMPT = (
+    "你是健康报告指标归一化归类助手。给定一个报告中的原始指标/菌属/食材名称,"
+    "把它归类为统一指标字典中的一个标准定义。只输出 JSON:"
+    '{"code": "indicator.<类别>.<标准名>" | "bacteria.<标准名>" | "food.<标准名>", '
+    '"name": "标准显示名", "category": "分类"}。'
+    "若候选列表非空,优先从候选中选择语义最接近的标准 code。"
+)
+
+
+@router.post("/indicator/classify", response_model=ClassifyResponse)
+async def classify_indicator(req: ClassifyRequest):
+    logger.info("indicator_classify: source=%s raw=%s", req.source_type, req.raw_name)
+    llm = get_llm_instance()
+    prompt = f"来源类型: {req.source_type}\n原始名称: {req.raw_name}\n"
+    if req.candidates:
+        prompt += "候选标准定义: " + ", ".join(req.candidates) + "\n"
+    try:
+        messages = [
+            SystemMessage(content=SYSTEM_PROMPT),
+            HumanMessage(content=prompt),
+        ]
+        response = await llm.ainvoke(messages)
+        text = response.content.strip()
+        if "```json" in text:
+            text = text.split("```json")[1].split("```")[0].strip()
+        elif "```" in text:
+            text = text.split("```")[1].strip()
+        data = json.loads(text)
+        return ClassifyResponse(data=data)
+    except Exception as e:
+        logger.error("指标归类失败: %s", e, exc_info=True)
+        return ClassifyResponse(code=500, message=f"归类失败: {str(e)}", data={})

+ 33 - 0
cfc-langgraph/app/api/innate_portrait.py

@@ -0,0 +1,33 @@
+from fastapi import APIRouter
+from pydantic import BaseModel
+from typing import Any, Dict, Optional
+from app.graphs.innate_portrait_graph import InnatePortraitAgent
+import logging
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["innate"])
+
+_agent: InnatePortraitAgent = None
+
+
+class InnateReadingRequest(BaseModel):
+    portrait: Dict[str, Any]
+
+
+class InnateReadingResponse(BaseModel):
+    reading: str
+    generated_at: Optional[str] = None
+
+
+def get_agent() -> InnatePortraitAgent:
+    global _agent
+    if _agent is None:
+        _agent = InnatePortraitAgent()
+    return _agent
+
+
+@router.post("/innate/reading", response_model=InnateReadingResponse)
+async def innate_reading(req: InnateReadingRequest):
+    agent = get_agent()
+    result = await agent.run(req.portrait)
+    return InnateReadingResponse(reading=result.get("reading", ""))

+ 263 - 0
cfc-langgraph/app/api/knowledge_base.py

@@ -0,0 +1,263 @@
+"""向量知识库管理接口 - 直接操作 ChromaDB"""
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+from typing import Optional, List
+import logging
+import asyncio
+import os
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/v1/knowledge-base", tags=["knowledge-base"])
+
+# 后台同步任务引用
+_sync_task = None
+
+
+class DocumentInfo(BaseModel):
+    id: str
+    source: str
+    title: str
+    content: str = ""
+    content_preview: str = ""
+    metadata: dict = {}
+
+
+class ListRequest(BaseModel):
+    source: Optional[str] = None
+    keyword: Optional[str] = None
+    page: int = 1
+    size: int = 20
+
+
+class UpdateDocumentRequest(BaseModel):
+    content: str
+    title: Optional[str] = None
+    metadata_override: Optional[dict] = None
+
+
+@router.post("/stats")
+async def get_stats():
+    """获取向量库统计信息"""
+    try:
+        from app.rag.retriever import RagRetriever
+        from app.rag.embeddings import get_embeddings
+        from app.config import settings
+        from langchain_chroma import Chroma
+
+        retriever = RagRetriever()
+        collection = retriever.vectorstore._collection
+        count = collection.count()
+
+        # 按 source 统计(兼容新旧两种 metadata 字段:source / type)
+        all_data = collection.get(include=["metadatas"])
+        metas = all_data.get("metadatas") or []
+        source_counts = {}
+        type_counts = {}
+        for meta in metas:
+            if not meta:
+                continue
+            src = meta.get("source") or meta.get("type") or "unknown"
+            source_counts[src] = source_counts.get(src, 0) + 1
+            doc_type = meta.get("type") or meta.get("source") or "unknown"
+            type_counts[doc_type] = type_counts.get(doc_type, 0) + 1
+
+        return {
+            "total": count,
+            "by_source": source_counts,
+            "by_type": type_counts,
+            "last_sync": _load_sync_state(),
+        }
+    except Exception as e:
+        logger.error("获取向量库统计失败: %s", e)
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+@router.post("/documents")
+async def list_documents(req: ListRequest):
+    """分页列出向量库文档"""
+    try:
+        from app.rag.retriever import RagRetriever
+        from app.rag.embeddings import get_embeddings
+        from app.config import settings
+        from langchain_chroma import Chroma
+
+        retriever = RagRetriever()
+        collection = retriever.vectorstore._collection
+
+        # 构建过滤条件(兼容新旧两种 metadata 字段:source / type)
+        where_filter = None
+        if req.source:
+            where_filter = {"$or": [{"source": req.source}, {"type": req.source}]}
+
+        # 使用 get() 分页获取,避免加载全部 embedding
+        limit = req.size
+        offset = (req.page - 1) * req.size
+
+        result = collection.get(
+            where=where_filter,
+            include=["documents", "metadatas"],
+            limit=limit,
+            offset=offset,
+        )
+
+        ids = result.get("ids") or []
+        docs = result.get("documents") or []
+        metas = result.get("metadatas") or []
+
+        documents = []
+        for i, doc_id in enumerate(ids):
+            meta = metas[i] if i < len(metas) else {}
+            content = docs[i] if i < len(docs) else ""
+            # 截取内容预览
+            preview = content[:200] + "..." if len(content) > 200 else content
+            documents.append(DocumentInfo(
+                id=doc_id,
+                source=meta.get("source") or meta.get("type") or "unknown",
+                title=meta.get("title", ""),
+                content=content,
+                content_preview=preview,
+                metadata=meta,
+            ))
+
+        # 获取总数
+        count_result = collection.get(
+            where=where_filter,
+            include=[],
+        )
+        total = len(count_result.get("ids", []))
+
+        return {
+            "total": total,
+            "page": req.page,
+            "size": req.size,
+            "documents": documents,
+        }
+    except Exception as e:
+        logger.error("列出文档失败: %s", e)
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+@router.delete("/source/{source_prefix}")
+async def delete_by_source(source_prefix: str):
+    """删除指定 source 前缀的所有文档"""
+    try:
+        from app.rag.retriever import RagRetriever
+        from app.rag.embeddings import get_embeddings
+        from app.config import settings
+        from langchain_chroma import Chroma
+
+        retriever = RagRetriever()
+        collection = retriever.vectorstore._collection
+
+        # 兼容新旧两种 metadata 字段:source / type
+        existing = collection.get(
+            where={"$or": [{"source": source_prefix}, {"type": source_prefix}]},
+            include=[],
+        )
+        ids = existing.get("ids", []) or []
+
+        if not ids:
+            return {"deleted": 0, "message": f"无 {source_prefix} 文档"}
+
+        collection.delete(ids=ids)
+        logger.info("已删除 source=%s 的 %d 个文档", source_prefix, len(ids))
+
+        return {"deleted": len(ids), "source": source_prefix}
+    except Exception as e:
+        logger.error("删除文档失败: %s", e)
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+@router.post("/sync")
+async def trigger_sync():
+    """触发一次完整知识库同步"""
+    global _sync_task
+
+    try:
+        # 如果已有同步任务在运行,返回提示
+        if _sync_task and not _sync_task.done():
+            return {"status": "running", "message": "同步任务已在运行中"}
+
+        _sync_task = asyncio.create_task(_run_sync())
+        return {"status": "started", "message": "已启动知识库同步任务"}
+    except Exception as e:
+        logger.error("触发同步失败: %s", e)
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+async def _run_sync():
+    """执行完整同步"""
+    try:
+        from app.tasks.knowledge_sync import sync_knowledge_base
+        await sync_knowledge_base()
+        logger.info("知识库同步完成")
+    except Exception as e:
+        logger.error("知识库同步失败: %s", e)
+
+
+@router.put("/document/{doc_id}")
+async def update_document(doc_id: str, req: UpdateDocumentRequest):
+    """更新单个文档内容(先获取原 metadata,再删除重建,保持 ID 不变)"""
+    try:
+        from app.rag.retriever import RagRetriever
+        from app.rag.embeddings import get_embeddings
+        from app.config import settings
+        from langchain_chroma import Chroma
+
+        retriever = RagRetriever()
+        collection = retriever.vectorstore._collection
+
+        # 先获取原文档 metadata,避免删除后丢失
+        old_result = collection.get(ids=[doc_id], include=["metadatas", "documents"])
+        old_metas = old_result.get("metadatas") or []
+        old_docs = old_result.get("documents") or []
+
+        if not old_metas:
+            raise HTTPException(status_code=404, detail="文档不存在")
+
+        original_meta = old_metas[0]
+        original_content = old_docs[0] if old_docs else ""
+
+        # 删除旧文档
+        collection.delete(ids=[doc_id])
+        logger.info("已删除旧文档: %s", doc_id)
+
+        # 构建新文档:保留原有 metadata,仅覆盖 content/title
+        meta = req.metadata_override or {}
+        # 保留原有 source/type/title 等字段,除非显式覆盖
+        for k, v in original_meta.items():
+            if k not in meta:
+                meta[k] = v
+
+        if req.title:
+            meta["title"] = req.title
+
+        # 使用原 ID 重新写入(显式传 ids,避免生成新 ID)
+        from langchain_core.documents import Document
+        doc = Document(page_content=req.content, metadata=meta)
+        await retriever.vectorstore.aadd_documents([doc], ids=[doc_id])
+        logger.info("已更新文档: %s", doc_id)
+
+        return {"success": True, "message": "文档已更新", "doc_id": doc_id}
+    except HTTPException:
+        raise
+    except Exception as e:
+        logger.error("更新文档失败: %s", e)
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+def _load_sync_state() -> str:
+    """加载上次同步时间"""
+    try:
+        import json
+        from app.config import settings
+        import os
+        sync_file = os.path.join(settings.chroma_db_path, ".sync_state")
+        if os.path.exists(sync_file):
+            with open(sync_file) as f:
+                state = json.load(f)
+                return state.get("last_sync", "未知")
+    except Exception:
+        pass
+    return "未知"

+ 38 - 0
cfc-langgraph/app/api/logs.py

@@ -0,0 +1,38 @@
+"""请求日志查询接口"""
+from fastapi import APIRouter
+from app.middleware import get_request_log, clear_request_log
+
+router = APIRouter(tags=["logs"])
+
+
+@router.get("/api/v1/logs")
+async def list_logs(
+    limit: int = 100,
+    path: str = None,
+    method: str = None,
+    status: int = None,
+):
+    """
+    获取请求日志(最近 N 条)
+    - limit: 返回条数(默认100,最大500)
+    - path: 路径过滤(支持模糊)
+    - method: 方法过滤(GET/POST)
+    - status: 状态码过滤
+    """
+    logs = get_request_log()
+    if limit and 0 < limit <= 500:
+        logs = logs[:limit]
+    if path:
+        logs = [l for l in logs if path.lower() in l.get("path", "").lower()]
+    if method:
+        logs = [l for l in logs if l.get("method", "").upper() == method.upper()]
+    if status:
+        logs = [l for l in logs if l.get("status") == status]
+    return {"total": len(get_request_log()), "count": len(logs), "logs": logs}
+
+
+@router.post("/api/v1/logs/clear")
+async def clear_logs():
+    """清空请求日志"""
+    n = clear_request_log()
+    return {"cleared": n}

+ 355 - 0
cfc-langgraph/app/api/meal.py

@@ -0,0 +1,355 @@
+import uuid
+import json
+import logging
+import re
+from fastapi import APIRouter
+from app.models.meal import (
+    FoodRecognizeRequest,
+    FoodRecognizeResponse,
+    FoodsItem,
+    MenuGenerateRequest,
+    MenuGenerateResponse,
+)
+from app.config import settings
+from app.prompt_service import get_prompt
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["meal"])
+
+FOOD_RECOGNIZE_TEMPLATE = """请识别以下图片中的主要食材(3-8种),按置信度排序。
+返回 JSON 数组格式,不要包含其他内容:
+[{{"name": "食材名称", "confidence": 0.95, "category": "蔬菜/水果/肉禽/水产/蛋奶/谷物/调味/其他"}}]
+
+图片链接: {image_url}
+要求: 只返回 JSON 数组,不要有任何其他文字。"""
+
+MENU_GENERATE_TEMPLATE = """请为{participant_count}人生成{date}的一日三餐菜单。
+
+可用食材: {foods_text}
+用餐人数: {participant_count}人
+{constraints_text}
+
+请返回 JSON 格式:
+{{"meals": [{{"type": "breakfast", "name": "早餐", "dishes": [{{"name": "菜品名", "ingredients": [{{"name": "食材", "grams": 100}}], "cooking_method": "做法一句话", "nutrition": {{"calories": 200}}}}]}}]}}
+
+要求:
+1. 午餐和晚餐按上方约束给出的菜数配菜(D(N)=4+max(0,N-3) 道菜 + 1 道汤,汤恒 1 且不计入菜数、只加菜不加汤),早餐维持 1-2 道
+2. 食材用量按{participant_count}人份计算
+3. 营养均衡,考虑健康目标
+4. 只用提供的食材
+5. 每道菜用 type 字段标注 dish(菜)或 soup(汤),汤恰好 1 道且排在最后
+6. 只返回 JSON,不要其他文字"""
+
+
+# Java 侧个性化画像字段 -> prompt 约束标签。同一标签可有多个别名(驼峰 / 下划线)。
+_CONSTRAINT_ALIASES = (
+    (("allergies",), "禁忌"),
+    (("diseases",), "疾病禁忌"),
+    (("medications",), "用药禁忌"),
+    (("healthGoals", "health_goals"), "健康目标"),
+    (("cuisinePrefs", "cuisine_pref"), "菜系偏好"),
+    (("flavorPrefs", "flavor_pref"), "口味偏好"),
+    (("spiceLevels", "spice_level"), "辣度偏好"),
+    (("mustEat", "must_eat"), "优先食材(用户喜好,优先安排)"),
+)
+_TOKEN_SEPARATORS = re.compile(r"[,,、;;]+")
+
+
+def _as_text(value):
+    """把约束值安全转成文本;列表/字典取元素;空值返回空串;任何异常都不外抛。"""
+    if value is None:
+        return ""
+    if isinstance(value, str):
+        return value.strip()
+    if isinstance(value, (list, tuple, set)):
+        items = value
+    elif isinstance(value, dict):
+        items = value.values()
+    else:
+        items = (value,)
+    parts = []
+    for item in items:
+        try:
+            text = str(item).strip()
+        except Exception:
+            continue
+        if text:
+            parts.append(text)
+    return ", ".join(parts)
+
+
+def _split_tokens(text):
+    """把一行约束值切成去重用的 token(兼容中英文逗号/顿号/分号)。"""
+    tokens = []
+    for token in _TOKEN_SEPARATORS.split(text):
+        token = token.strip()
+        if token and token not in tokens:
+            tokens.append(token)
+    return tokens
+
+
+def _merge_constraints(constraints, raw):
+    """把 req.constraints 增量合并进现有 constraints:按标签去重、忽略空值。"""
+    if not isinstance(raw, dict):
+        return
+    for keys, label in _CONSTRAINT_ALIASES:
+        values = []
+        for key in keys:
+            text = _as_text(raw.get(key))
+            if text and text not in values:
+                values.append(text)
+        if not values:
+            continue
+        prefix = label + ": "
+        covered = set()
+        for line in constraints:
+            if isinstance(line, str) and line.startswith(prefix):
+                covered.update(_split_tokens(line[len(prefix):]))
+        fresh = []
+        for value in values:
+            for token in _split_tokens(value):
+                if token and token not in covered and token not in fresh:
+                    fresh.append(token)
+        if fresh:
+            constraints.append(prefix + ", ".join(fresh))
+
+
+def _append_variation_constraints(constraints, req):
+    """追加「换花样」相关约束:最近已用菜名 + 变化种子。"""
+    names = getattr(req, "exclude_dish_names", None)
+    if isinstance(names, str):
+        names = [names]
+    elif isinstance(names, (list, tuple, set)):
+        names = list(names)
+    else:
+        names = []
+    cleaned = []
+    for name in names:
+        try:
+            text = str(name).strip()
+        except Exception:
+            continue
+        if text and text not in cleaned:
+            cleaned.append(text)
+        if len(cleaned) >= 20:
+            break
+    if cleaned:
+        constraints.append("换花样:避免使用最近已采用的菜名:" + "、".join(cleaned))
+
+    seed = getattr(req, "variation_seed", None)
+    if seed is not None:
+        constraints.append(f"本次生成变化种子:{seed},请让菜品搭配与上次不同")
+
+
+@router.post("/food/recognize", response_model=FoodRecognizeResponse)
+async def recognize_food(req: FoodRecognizeRequest):
+    """食材识别: 上传图片 URL, 返回识别食材列表"""
+    trace_id = str(uuid.uuid4())
+    try:
+        from langchain_openai import ChatOpenAI
+        from langchain_core.messages import HumanMessage, SystemMessage
+
+        llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=0,
+        )
+
+        role = await get_prompt("food_recognize_role") or "你是一个专业的食材识别助手。"
+        template = await get_prompt("food_recognize") or FOOD_RECOGNIZE_TEMPLATE
+        try:
+            prompt = template.format(image_url=req.image_url)
+        except (KeyError, IndexError, ValueError):
+            logger.warning("Java 配置的 food_recognize 模板缺少占位符,回退本地模板")
+            prompt = FOOD_RECOGNIZE_TEMPLATE.format(image_url=req.image_url)
+
+        response = llm.invoke([
+            SystemMessage(content=role),
+            HumanMessage(content=prompt),
+        ])
+
+        text = response.content.strip()
+        try:
+            foods = json.loads(text)
+        except json.JSONDecodeError:
+            match = re.search(r'\[[\s\S]*\]', text)
+            foods = json.loads(match.group()) if match else []
+
+        foods_list = []
+        for item in foods:
+            if isinstance(item, dict):
+                foods_list.append(FoodsItem(
+                    name=item.get("name", "未知"),
+                    confidence=float(item.get("confidence", 0.5)),
+                    category=item.get("category", "other"),
+                ))
+
+        return FoodRecognizeResponse(foods=foods_list, raw_response=text, trace_id=trace_id)
+    except Exception as e:
+        logger.error("食材识别失败: %s", e, exc_info=True)
+        return FoodRecognizeResponse(foods=[], trace_id=trace_id)
+
+
+@router.post("/menu/generate", response_model=MenuGenerateResponse)
+async def generate_menu(req: MenuGenerateRequest):
+    """菜单生成: 根据食材和用餐人数生成一日三餐菜单"""
+    trace_id = str(uuid.uuid4())
+    try:
+        from langchain_openai import ChatOpenAI
+        from langchain_core.messages import HumanMessage, SystemMessage
+
+        try:
+            selected_foods = json.loads(req.selected_foods) if req.selected_foods else []
+        except json.JSONDecodeError:
+            selected_foods = []
+
+        try:
+            participants = json.loads(req.participants) if req.participants else []
+        except json.JSONDecodeError:
+            participants = []
+
+        participant_count = len(participants) if participants else 1
+        foods_text = ", ".join([f.get("name", "") for f in selected_foods]) if selected_foods else "根据可用食材"
+
+        constraints = []
+        if req.allergies:
+            constraints.append(f"禁忌: {req.allergies}")
+        if req.health_goals:
+            constraints.append(f"健康目标: {req.health_goals}")
+        if req.cuisine_pref:
+            constraints.append(f"菜系偏好: {req.cuisine_pref}")
+        if req.spice_level is not None:
+            constraints.append(f"辣度: {req.spice_level}/5")
+
+        # 个性化画像:把 Java 下发的 constraints 字典增量合并进同一份 constraints,
+        # 不新增占位符、不改动 prompt 模板,旧调用方不传该字段时行为完全不变。
+        try:
+            _merge_constraints(constraints, getattr(req, "constraints", None))
+        except Exception as e:
+            logger.warning("合并用户个性化约束失败,忽略该字段: %s", e)
+        try:
+            _append_variation_constraints(constraints, req)
+        except Exception as e:
+            logger.warning("合并换花样约束失败,忽略该字段: %s", e)
+
+        # 菜数要求(CR-C / R-05):注入既有 {constraints_text} 占位符,不新增占位符(F-18),
+        # 因此 DB 模板(get_prompt)与本地模板两个来源同时生效;不依赖 prompt 的正确性,
+        # 菜数硬保证由 Java DietRecommendationService.normalizeMenu 兜底。
+        # Java AiGateway 传 dish_count = D(N);旧调用方不传时按 participant_count 现算,行为一致。
+        effective_dish_count = req.dish_count if req.dish_count is not None else 4 + max(0, participant_count - 3)
+        constraints.append(
+            f"菜数硬要求: 午餐和晚餐各需 {effective_dish_count} 道菜 + 1 道汤"
+            f"(D(N)=4+max(0,N-3),汤恒 1 且不计入菜数、只加菜不加汤;"
+            f"汤标 type=soup、菜标 type=dish,汤恰好 1 道且排在最后);早餐维持 1-2 道。"
+        )
+        constraints_text = "\n".join(constraints) if constraints else "无特殊限制"
+
+        role = await get_prompt("menu_generate_role") or "你是一个专业营养师和厨师,擅长根据食材和健康目标设计食谱。"
+        template = await get_prompt("menu_generate") or MENU_GENERATE_TEMPLATE
+        try:
+            prompt = template.format(
+                participant_count=participant_count,
+                date=req.date,
+                foods_text=foods_text,
+                constraints_text=constraints_text,
+            )
+        except (KeyError, IndexError, ValueError):
+            logger.warning("Java 配置的 menu_generate 模板缺少占位符,回退本地模板")
+            prompt = MENU_GENERATE_TEMPLATE.format(
+                participant_count=participant_count,
+                date=req.date,
+                foods_text=foods_text,
+                constraints_text=constraints_text,
+            )
+
+        llm = ChatOpenAI(
+            # agnes-2.5-flash:非推理模型,菜单生成 11s(deepseek 推理型会占满 token 导致 content 为空)
+            model="agnes-2.5-flash",
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=0.7,
+            # 一日三餐 D(N)+1 道菜,每道含食材/做法/营养,中文 JSON 很长;
+            # 3000 token 会截断在晚餐中途,导致 Java 侧归一化失败→整份兜底。
+            max_tokens=8000,
+        )
+
+        response = llm.invoke([
+            SystemMessage(content=role),
+            HumanMessage(content=prompt),
+        ])
+
+        text = response.content.strip()
+
+        def _balanced_json(t):
+            """从 t 中截取第一个花括号配平的完整 JSON;找不到返回 None。"""
+            start = t.find('{')
+            if start < 0:
+                return None
+            depth = 0
+            in_string = False
+            escape = False
+            for i in range(start, len(t)):
+                ch = t[i]
+                if in_string:
+                    if escape:
+                        escape = False
+                    elif ch == '\\':
+                        escape = True
+                    elif ch == '"':
+                        in_string = False
+                    continue
+                if ch == '"':
+                    in_string = True
+                elif ch == '{':
+                    depth += 1
+                elif ch == '}':
+                    depth -= 1
+                    if depth == 0:
+                        return t[start:i + 1]
+            return None
+
+        def _valid_json_str(t):
+            try:
+                json.loads(t)
+                return True
+            except Exception:
+                return False
+
+        menu_json = None
+        # 优先:模型包裹在 ```json ... ``` 或前后有说明文字时,贪婪取首尾大括号
+        match = re.search(r'\{[\s\S]*\}', text)
+        if match and _valid_json_str(match.group()):
+            menu_json = match.group()
+        if menu_json is None:
+            # 兜底:按花括号配平截取(处理尾部截断但未闭合的片段)
+            candidate = _balanced_json(text)
+            if candidate and _valid_json_str(candidate):
+                menu_json = candidate
+        if menu_json is None:
+            # 最后兜底:若模型返回截断 JSON,尝试截到最后一个完整 dish 对象后补齐括号
+            candidate = _balanced_json(text)
+            if candidate:
+                # 去掉末尾不完整的 dish/ingredients 片段,逐级补齐 ] }
+                fixed = candidate.rstrip()
+                # 逐步回退到最近的 '}' 并补齐剩余括号
+                while fixed and not _valid_json_str(fixed):
+                    cuts = max(fixed.rfind('}'), fixed.rfind(']'))
+                    if cuts <= 0:
+                        break
+                    fixed = fixed[:cuts + 1]
+                    # 补齐缺失的闭合括号
+                    opens = fixed.count('{') - fixed.count('}')
+                    fixed = fixed + '}' * max(0, opens)
+                if _valid_json_str(fixed):
+                    menu_json = fixed
+                    logger.warning("菜单 JSON 被截断,已修复后返回: trace_id=%s", trace_id)
+        if menu_json is None:
+            logger.warning("菜单 JSON 无法解析,返回空菜单让 Java 走兜底: trace_id=%s, text_head=%s",
+                           trace_id, text[:120])
+            menu_json = '{"meals": []}'
+
+        return MenuGenerateResponse(menu_json=menu_json, trace_id=trace_id)
+    except Exception as e:
+        logger.error("菜单生成失败: %s", e, exc_info=True)
+        return MenuGenerateResponse(menu_json='{"meals": []}', trace_id=trace_id)

+ 56 - 0
cfc-langgraph/app/api/portrait.py

@@ -0,0 +1,56 @@
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+from app.graphs.portrait_generation_graph import get_portrait_graph
+import logging
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/portrait", tags=["portrait"])
+
+
+class PortraitGenerateRequest(BaseModel):
+    user_id: int
+    member_id: int | None = None
+    previous_portrait: str | None = None
+    profile_snapshot: dict | None = None
+    behavior_summary: dict | None = None
+
+
+@router.post("/generate")
+async def generate_portrait(req: PortraitGenerateRequest):
+    """AI 生成用户画像(首次生成)"""
+    try:
+        graph = get_portrait_graph()
+        state = {
+            "user_id": req.user_id,
+            "member_id": req.member_id,
+            "previous_portrait": None,
+            "profile_snapshot": req.profile_snapshot,
+            "behavior_summary": req.behavior_summary,
+            "portrait_text": None,
+        }
+        result = await graph.ainvoke(state)
+        return {"portrait_text": result["portrait_text"]}
+    except Exception as e:
+        logger.exception("画像生成失败")
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+@router.post("/regenerate")
+async def regenerate_portrait(req: PortraitGenerateRequest):
+    """AI 重画用户画像(参考旧画像)"""
+    try:
+        graph = get_portrait_graph()
+        state = {
+            "user_id": req.user_id,
+            "member_id": req.member_id,
+            "previous_portrait": req.previous_portrait,
+            "profile_snapshot": req.profile_snapshot,
+            "behavior_summary": req.behavior_summary,
+            "portrait_text": None,
+        }
+        result = await graph.ainvoke(state)
+        return {"portrait_text": result["portrait_text"]}
+    except Exception as e:
+        logger.exception("画像重画失败")
+        raise HTTPException(status_code=500, detail=str(e))

+ 89 - 0
cfc-langgraph/app/api/question_generate.py

@@ -0,0 +1,89 @@
+"""五维自检题目生成 API
+
+提供基于用户画路径的智能题目生成服务,包含:
+- AI生成 20 道情境化问卷题目
+- 支持自定义维度分配
+- 支持历史记题目去重
+- 与现有 15 题固定题库并存"""
+
+import logging
+from fastapi import APIRouter
+from pydantic import BaseModel
+from typing import Any, Dict, List, Optional
+from app.graphs.question_generation_graph import run_question_gen
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["question-generate"])
+
+
+class QuestionGenRequest(BaseModel):
+    """题目生成请求"""
+    user_id: int
+    count: int = 20  # 题目总数,默认20(满足系统≥10题门槛)
+    difficulty: str = "balanced"  # balanced/easy/hard/contextual
+    dimensions: Optional[List[str]] = None  # 可选指定维度,如 ["body", "wisdom"]
+    exclude_ids: Optional[List[int]] = None  # 历史题目ID列表,用于避免重复
+
+
+class QuestionGenResponse(BaseModel):
+    """题目生成响应"""
+    questions: List[Dict[str, Any]]
+    total_generated: int
+    generation_time: float
+    rationale: str
+    dimension_distribution: Dict[str, int]
+    fallback_used: bool
+
+
+@router.post("/question-generate", response_model=QuestionGenResponse)
+async def question_generate(req: QuestionGenRequest):
+    """AI生成五维自检题目
+    
+    根据用户画像生成 20 道情境化问卷题目,满足系统最低门槛:
+    - 总题数≥10
+    - 每个维度至少 1 题
+    
+    请求体:
+    - user_id: 必填,用户 ID
+    - count: 可选,题目总数,默认 20
+    - difficulty: 可选,难度提示,默认 "balanced"
+    - dimensions: 可选,指定维度列表,如 ["body", "wisdom"]
+    - exclude_ids: 可选,历史题目 ID 列表,用于避免重复提问
+    
+    响应体:
+    - questions: 生成的题目列表,每题包含 id, dimension, text, options
+    - total_generated: 实际生成数量
+    - generation_time: 生成耗时(秒)
+    - rationale: 生成 rationale,解释维度选择逻辑
+    - dimension_distribution: 各维度题目数量分布
+    - fallback_used: 是否使用了降级方案(LLM失败回退到本地题库)
+    """
+    try:
+        result = await run_question_gen(
+            user_id=user_id,
+            count=req.count,
+            difficulty=req.difficulty,
+            dimensions=req.dimensions,
+            exclude_ids=req.exclude_ids,
+        )
+        
+        return QuestionGenResponse(
+            questions=result.get("questions", []),
+            total_generated=result.get("total_generated", 0),
+            generation_time=result.get("generation_time", 0.0),
+            rationale=result.get("rationale", ""),
+            dimension_distribution=result.get("dimension_distribution", {}),
+            fallback_used=result.get("fallback_used", False),
+        )
+        
+    except Exception as e:
+        logger.error(f"AI 生成题目失败: {e}", exc_info=True)
+        # 降级:返回空结果,前端可据此提示用户或使用固定题库
+        return QuestionGenResponse(
+            questions=[],
+            total_generated=0,
+            generation_time=0.0,
+            rationale=f"生成失败: {str(e)},将使用固定题库",
+            dimension_distribution={},
+            fallback_used=True,
+        )

+ 42 - 0
cfc-langgraph/app/api/recommend.py

@@ -0,0 +1,42 @@
+import uuid
+from fastapi import APIRouter
+from app.models.recommend import RecommendRequest, RecommendResponse, RecommendItem
+from app.graphs.recommend_graph import RecommendAgent
+import logging
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["recommend"])
+
+_agent: RecommendAgent = None
+
+
+def get_agent() -> RecommendAgent:
+    global _agent
+    if _agent is None:
+        _agent = RecommendAgent()
+    return _agent
+
+
+@router.post("/recommend", response_model=RecommendResponse)
+async def recommend(req: RecommendRequest):
+    """营养推荐: Agent 搜索+LLM 解释"""
+    trace_id = str(uuid.uuid4())
+    try:
+        agent = get_agent()
+        result = await agent.run(query=req.query, tags=req.tags, limit=req.limit)
+
+        items_data = result.get("items", [])
+        items = []
+        for item in items_data:
+            items.append(RecommendItem(
+                type=item.get("type", "product"),
+                id=item.get("id", 0),
+                name=item.get("name", ""),
+                description=item.get("description", ""),
+                reason=item.get("reason", ""),
+            ))
+
+        return RecommendResponse(items=items, source="agent", trace_id=trace_id)
+    except Exception as e:
+        logger.error("RecommendAgent 调用失败: %s", e, exc_info=True)
+        return RecommendResponse(items=[], source="error", trace_id=trace_id)

+ 136 - 0
cfc-langgraph/app/api/report_parse.py

@@ -0,0 +1,136 @@
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+from typing import Optional, Any
+from app.agents.report_parse_agent import ReportParseAgent
+import logging
+import os
+import json
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["report_parse"])
+_agent = None
+
+
+def get_agent():
+    global _agent
+    if _agent is None:
+        _agent = ReportParseAgent()
+    return _agent
+
+
+class ParseRequest(BaseModel):
+    file_path: str
+    family_id: Optional[int] = None
+    user_id: Optional[int] = None
+    indicators: Optional[list[str]] = None
+
+
+class ParseResponse(BaseModel):
+    code: int = 200
+    message: str = "ok"
+    data: dict = {}
+
+
+@router.post("/report/parse", response_model=ParseResponse)
+async def parse_report(req: ParseRequest):
+    if not os.path.exists(req.file_path):
+        raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
+
+    logger.info("report_parse: file_path=%s family_id=%s user_id=%s",
+                req.file_path, req.family_id, req.user_id)
+    agent = get_agent()
+    try:
+        result = await agent.parse(req.file_path, req.indicators)
+        return ParseResponse(data=result)
+    except Exception as e:
+        logger.error("报告解析失败: %s", e, exc_info=True)
+        return ParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
+
+
+class GenericParseRequest(BaseModel):
+    file_path: str
+    extra_context: Optional[dict] = None
+
+
+class GenericParseResponse(BaseModel):
+    code: int = 200
+    message: str = "ok"
+    data: dict = {}
+
+
+@router.post("/report/parse-generic", response_model=GenericParseResponse)
+async def parse_report_generic(req: GenericParseRequest):
+    """通用报告 LLM 兜底解析。
+
+    适用于指纹检测未匹配的未知类型报告。
+    直接交给 LLM 提取结构化数据,不经过算法预解析。
+    """
+    if not os.path.exists(req.file_path):
+        raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
+
+    logger.info("report_parse_generic: file_path=%s", req.file_path)
+    agent = get_agent()
+    try:
+        result = await agent.parse_generic(req.file_path, req.extra_context)
+        return GenericParseResponse(data=result)
+    except Exception as e:
+        logger.error("通用报告解析失败: %s", e, exc_info=True)
+        return GenericParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
+
+
+class TypedParseRequest(BaseModel):
+    file_path: str
+    report_type: str = "auto"
+    extra_context: Optional[dict] = None
+    indicators: Optional[list[str]] = None
+
+
+class TypedParseResponse(BaseModel):
+    code: int = 200
+    message: str = "ok"
+    data: dict = {}
+
+
+@router.post("/report/parse-typed", response_model=TypedParseResponse)
+async def parse_report_typed(req: TypedParseRequest):
+    """按报告类型解析。
+
+    支持的报告类型:
+    - auto: 自动检测(默认)
+    - brain_status: 脑状态测量报告
+    - cognitive_aptitude: 先天智力潜能/皮纹学测评报告
+    - scanned_image: 扫描图片 PDF(无文字层,需多模态 LLM)
+    - generic: 通用 LLM 解析
+    - gut_flora: 肠道菌群报告(算法解析 + LLM 兜底)
+    """
+    if not os.path.exists(req.file_path):
+        raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
+
+    logger.info("report_parse_typed: file_path=%s type=%s",
+                req.file_path, req.report_type)
+    agent = get_agent()
+    try:
+        result = await agent.parse_by_type(req.file_path, req.report_type, req.extra_context, req.indicators)
+        return TypedParseResponse(data=result)
+    except Exception as e:
+        logger.error("类型报告解析失败: %s", e, exc_info=True)
+        return TypedParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
+
+
+class TypedParseRequest2(BaseModel):
+    file_path: str
+
+
+@router.post("/report/detect-type", response_model=TypedParseResponse)
+async def detect_report_type(req: TypedParseRequest2):
+    """检测报告类型,返回检测结果(不执行解析)。"""
+    if not os.path.exists(req.file_path):
+        raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
+
+    agent = get_agent()
+    try:
+        detected = agent._detect_report_type(req.file_path)
+        return TypedParseResponse(data={"detectedType": detected})
+    except Exception as e:
+        logger.error("报告类型检测失败: %s", e, exc_info=True)
+        return TypedParseResponse(code=500, message=f"检测失败: {str(e)}", data={})

+ 54 - 0
cfc-langgraph/app/api/self_check.py

@@ -0,0 +1,54 @@
+import logging
+from fastapi import APIRouter
+from pydantic import BaseModel
+from typing import Any, Dict, Optional
+from app.graphs.self_check_analysis_graph import get_graph
+from app.graphs.self_check_trend_graph import get_trend_graph
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["self-check"])
+
+
+class SelfCheckAnalysisRequest(BaseModel):
+    scores: Dict[str, Any]
+    question_ids: list
+    user_id: int
+    recent_history: Optional[list] = None
+
+
+class SelfCheckTrendRequest(BaseModel):
+    history: list
+    user_id: int
+
+
+@router.post("/self-check/analysis")
+async def self_check_analysis(req: SelfCheckAnalysisRequest):
+    graph = get_graph()
+    state = {
+        "scores": req.scores,
+        "question_ids": req.question_ids,
+        "user_id": req.user_id,
+        "recent_history": req.recent_history or [],
+        "advice": None,
+        "error": None,
+    }
+    result = await graph.ainvoke(state)
+    advice = result.get("advice") or {}
+    return {
+        "advice_json": advice.get("advice_json"),
+        "fallback_used": advice.get("fallback_used", True),
+        "error": result.get("error"),
+    }
+
+
+@router.post("/self-check/trend")
+async def self_check_trend(req: SelfCheckTrendRequest):
+    graph = get_trend_graph()
+    state = {"history": req.history, "user_id": req.user_id, "insight": None, "error": None}
+    result = await graph.ainvoke(state)
+    insight = result.get("insight") or {}
+    return {
+        "aiInsight": insight.get("aiInsight", ""),
+        "trendSummary": insight.get("trendSummary", ""),
+        "error": result.get("error"),
+    }

+ 109 - 0
cfc-langgraph/app/api/tongue.py

@@ -0,0 +1,109 @@
+from fastapi import APIRouter, UploadFile, File, Form
+from typing import Optional
+from app.agents.multimodal_agent import TongueDiagnosisAgent
+import logging
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/api/v1", tags=["tongue"])
+
+_agent: Optional[TongueDiagnosisAgent] = None
+
+
+def get_agent() -> TongueDiagnosisAgent:
+    global _agent
+    if _agent is None:
+        _agent = TongueDiagnosisAgent()
+    return _agent
+
+
+@router.post("/tongue/diagnose")
+async def tongue_diagnose(
+    file: UploadFile = File(...),
+    user_id: int = Form(...),
+    prompt_template: Optional[str] = Form(None),
+):
+    """舌诊分析: 上传舌苔图片, 返回分析结果"""
+    agent = get_agent()
+
+    import tempfile, os
+    ext = os.path.splitext(file.filename or "tongue.jpg")[1] or ".jpg"
+    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=ext)
+    content = await file.read()
+    tmp.write(content)
+    tmp.close()
+
+    try:
+        import base64
+        b64 = base64.b64encode(content).decode()
+        data_url = f"data:image/{ext[1:]};base64,{b64}"
+
+        result = await agent.diagnose(image_url=data_url, user_id=user_id, prompt_template=prompt_template)
+        return {"code": 200, "data": result}
+    except Exception as e:
+        logger.error("舌诊分析失败: %s", e, exc_info=True)
+        return {"code": 500, "message": "舌诊分析失败"}
+    finally:
+        os.unlink(tmp.name)
+
+
+# ── 舌象快速分类(纯颜色启发式,<50ms)────────────────────────────
+def _quick_tongue_detect(content: bytes) -> bool:
+    """基于颜色分布的轻量级舌象分类,避免调用 LLM。
+
+    判据:
+    1. 全图中偏红/暖色像素占比 >= 30%(舌体是红/粉色)
+    2. 白色/近白像素占比 < 65%(排除大面积白纸报告)
+    3. 纯黑文字像素占比 < 25%(排除文档/报告截图)
+    """
+    from PIL import Image
+    import io
+
+    try:
+        img = Image.open(io.BytesIO(content)).convert("RGB")
+        small = img.resize((200, 200), Image.LANCZOS)
+        pixels = list(small.getdata())
+        n = len(pixels)
+
+        reddish = warm = white_px = black_px = 0
+        for r, g, b in pixels:
+            if r > g * 1.15 and r > b * 1.15:
+                reddish += 1
+            if r > g and r > b and (r - b) > 15:
+                warm += 1
+            if r > 200 and g > 200 and b > 200:
+                white_px += 1
+            if r < 80 and g < 80 and b < 80:
+                black_px += 1
+
+        red_ratio = reddish / n
+        warm_ratio = warm / n
+        white_ratio = white_px / n
+        text_ratio = black_px / n
+
+        # 舌象:≥30% 偏红 + 白色占比不高 + 文字占比不高
+        is_tongue = (red_ratio >= 0.30) and (white_ratio < 0.65) and (text_ratio < 0.25)
+        logger.debug(
+            "舌象分类 [red=%.3f warm=%.3f white=%.3f text=%.3f] → %s",
+            red_ratio, warm_ratio, white_ratio, text_ratio, is_tongue,
+        )
+        return is_tongue
+    except Exception as e:
+        logger.warning("舌象颜色分析失败,降级为 false: %s", e)
+        return False
+
+
+@router.post("/tongue/detect")
+async def tongue_detect(file: UploadFile = File(...)):
+    """舌象照片分类: 判断上传图片是否为舌头(舌象)照片,用于图片上传分流。
+
+    返回 {"is_tongue": bool}。非舌象(报告截图/文档/其他部位)返回 false。
+    分类失败时返回 false(安全降级:走通用报告流程,不误伤正常报告)。
+    """
+    content = await file.read()
+    try:
+        is_tongue = _quick_tongue_detect(content)
+        logger.info("舌象分类结果 is_tongue=%s (filename=%s)", is_tongue, file.filename)
+        return {"code": 200, "data": {"is_tongue": is_tongue}}
+    except Exception as e:
+        logger.error("舌象分类失败: %s", e, exc_info=True)
+        return {"code": 200, "data": {"is_tongue": False}}

+ 0 - 0
cfc-langgraph/app/audio/__init__.py


+ 71 - 0
cfc-langgraph/app/audio/transcriber.py

@@ -0,0 +1,71 @@
+"""faster-whisper 本地 STT 引擎封装"""
+import os
+import logging
+import numpy as np
+import av
+from faster_whisper import WhisperModel
+
+logger = logging.getLogger(__name__)
+
+_model = None
+_loaded = False
+
+
+def init_model(model_size: str = "base", device: str = "cpu", compute_type: str = "int8"):
+    """初始化 faster-whisper 模型(启动时调用)"""
+    global _model, _loaded
+    if _loaded:
+        return
+    os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com")
+    logger.info("加载 faster-whisper 模型 %s (device=%s, compute=%s)...", model_size, device, compute_type)
+    _model = WhisperModel(model_size, device=device, compute_type=compute_type)
+    _loaded = True
+    logger.info("faster-whisper 模型加载完成")
+
+
+def transcribe_audio(file_path: str, language: str = "zh") -> dict:
+    """转写音频文件,返回 {text, language, language_probability, duration}"""
+    if not _model:
+        raise RuntimeError("faster-whisper 模型未初始化")
+
+    duration_sec = 0.0
+    try:
+        with av.open(file_path) as container:
+            stream = container.streams.audio[0]
+            audio_chunks = []
+            sample_cnt = 0
+            for frame in container.decode(audio=0):
+                arr = frame.to_ndarray()
+                sample_cnt += frame.samples
+                if arr.ndim > 1 and arr.shape[0] > 1:
+                    arr = np.mean(arr, axis=0)
+                else:
+                    arr = arr.reshape(-1)
+                audio_chunks.append(arr)
+            if not audio_chunks:
+                raise ValueError("音频文件无有效帧")
+            audio = np.concatenate(audio_chunks).astype(np.float32)
+            max_val = np.max(np.abs(audio))
+            if max_val > 0:
+                audio = audio / max_val
+            orig_rate = stream.sample_rate if stream.sample_rate else 44100
+            if orig_rate != 16000:
+                new_len = int(sample_cnt * 16000 / orig_rate)
+                audio = np.interp(
+                    np.linspace(0, sample_cnt - 1, new_len),
+                    np.arange(sample_cnt),
+                    audio
+                ).astype(np.float32)
+            duration_sec = len(audio) / 16000.0
+    except Exception as e:
+        logger.error("音频解码失败 %s: %s", file_path, e)
+        raise
+
+    segments, info = _model.transcribe(audio, language=language, beam_size=1, vad_filter=True)
+    text = "".join(seg.text for seg in segments).strip()
+    return {
+        "text": text,
+        "language": info.language,
+        "language_probability": round(float(info.language_probability), 4),
+        "duration": round(duration_sec, 2),
+    }

+ 74 - 0
cfc-langgraph/app/checkpointer.py

@@ -0,0 +1,74 @@
+"""
+共享的 LangGraph checkpointer 工厂。
+
+原实现使用 MemorySaver(纯内存),服务重启即丢失所有对话状态。
+这里改用 SQLite 持久化(AsyncSqliteSaver),支持异步调用,对话状态落盘,重启不丢。
+
+说明:LangGraph 官方 RedisSaver 依赖 RedisSearch 模块(FT.* 命令),
+当前 Redis 未安装该模块,故采用 SQLite 持久化作为务实替代。
+
+重要:AsyncSqliteSaver 内部绑定 asyncio.Lock + 当前事件循环(get_running_loop),
+必须在 FastAPI 的 running loop 内初始化(app startup 时调用 init_checkpointer),
+不能在临时 loop 中创建,否则后续 ainvoke 会报 "attached to a different loop"。
+"""
+import logging
+import os
+
+import aiosqlite
+from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
+
+logger = logging.getLogger(__name__)
+
+# SQLite 数据库文件路径:
+# - Docker 容器内 /data 为持久化卷(与 Chroma 同级),但需检查写权限
+# - 本地开发 fallback 到项目 data/ 目录
+# - 可用环境变量 CHECKPOINT_DB_PATH 覆盖
+_DEFAULT_DB_PATH = os.path.join(
+    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+    "data",
+    "checkpoints.db",
+)
+
+# 全局单例(由 init_checkpointer 在 startup 时填充)
+_saver: AsyncSqliteSaver | None = None
+
+
+def _resolve_db_path() -> str:
+    """解析数据库路径:优先环境变量,其次有写权限的目录。"""
+    # 1. 环境变量覆盖
+    env_path = os.environ.get("CHECKPOINT_DB_PATH")
+    if env_path:
+        return env_path
+
+    # 2. 尝试 /data(容器卷),需检查写权限
+    if os.path.isdir("/data") and os.access("/data", os.W_OK):
+        return "/data/checkpoints.db"
+
+    # 3. fallback 到项目 data 目录
+    return _DEFAULT_DB_PATH
+
+
+async def init_checkpointer() -> AsyncSqliteSaver:
+    """在运行中的事件循环内初始化 AsyncSqliteSaver(app startup 时调用)。"""
+    global _saver
+    if _saver is not None:
+        return _saver
+
+    db_path = _resolve_db_path()
+    os.makedirs(os.path.dirname(db_path), exist_ok=True)
+
+    conn = await aiosqlite.connect(db_path)
+    saver = AsyncSqliteSaver(conn)
+    await saver.setup()
+    _saver = saver
+    logger.info("LangGraph AsyncSqliteSaver 已初始化: %s", db_path)
+    return _saver
+
+
+def get_checkpointer() -> AsyncSqliteSaver:
+    """获取全局 AsyncSqliteSaver(须已通过 init_checkpointer 在 startup 初始化)。"""
+    if _saver is None:
+        raise RuntimeError(
+            "checkpointer 未初始化,请确保 app startup 已调用 init_checkpointer()"
+        )
+    return _saver

+ 54 - 0
cfc-langgraph/app/config.py

@@ -0,0 +1,54 @@
+from pydantic_settings import BaseSettings
+from typing import Optional
+
+
+class Settings(BaseSettings):
+    # LLM
+    llm_api_key: str
+    llm_base_url: str = "https://api.deepseek.com/v1"
+    llm_model: str = "deepseek-chat"
+    # 部分模型(如 kimi-k2.6)仅允许 temperature=1,统一从配置读取便于切换模型时调整
+    llm_temperature: float = 1.0
+
+    # Embedding
+    embedding_api_key: Optional[str] = None
+    embedding_base_url: Optional[str] = None
+    embedding_model: str = "text-embedding-v3"
+
+    # Java Backend
+    java_base_url: str = "http://localhost:9082"
+    java_context_url: Optional[str] = None
+
+    # LangSmith
+    langchain_tracing_v2: bool = False
+    langchain_api_key: Optional[str] = None
+    langchain_project: str = "cfc-langgraph"
+
+    # Service
+    service_host: str = "0.0.0.0"
+    service_port: int = 9000
+    log_level: str = "info"
+
+    # Dify Fallback
+    dify_base_url: Optional[str] = None
+    dify_tongue_api_key: Optional[str] = None
+
+    # Chroma
+    chroma_db_path: str = "./data/chroma_db"
+
+    model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
+
+    @property
+    def effective_embedding_api_key(self) -> str:
+        return self.embedding_api_key or self.llm_api_key
+
+    @property
+    def effective_embedding_base_url(self) -> str:
+        return self.embedding_base_url or self.llm_base_url
+
+    @property
+    def effective_java_context_url(self) -> str:
+        return self.java_context_url or f"{self.java_base_url}/api/ai/context"
+
+
+settings = Settings()

+ 0 - 0
cfc-langgraph/app/graphs/__init__.py


+ 97 - 0
cfc-langgraph/app/graphs/analysis_graph.py

@@ -0,0 +1,97 @@
+from typing import TypedDict, Optional
+from langgraph.graph import StateGraph, START, END
+from langgraph.checkpoint.memory import MemorySaver
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.tools.report_tools import get_report_detail, get_survey_data, get_dimension_scores
+from app.config import settings
+from app.prompt_service import get_prompt
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class AnalysisState(TypedDict):
+    report_id: int
+    user_id: int
+    focus: Optional[str]          # nutrition / gut / chronic / overall
+    report_data: Optional[dict]
+    survey_data: Optional[dict]
+    dimension_scores: Optional[dict]
+    analysis: Optional[str]
+    recommendations: list[str]
+
+
+ANALYSIS_SYSTEM_PROMPT = """你是一个儿童健康报告解读专家。根据健康报告数据和调研问卷, 提供专业、易懂的分析。
+
+分析原则:
+1. 用通俗语言解释各项指标含义
+2. 关注异常指标, 给出改善建议
+3. 结合问卷数据提供个性化分析
+4. 五维能量(身/心/智/行/富)角度解读整体状况
+5. 输出格式: 总体评估 → 分项分析 → 改善建议
+"""
+
+
+def create_analysis_graph():
+    """创建报告解读 StateGraph"""
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=settings.llm_temperature,
+    )
+    llm_with_tools = llm.bind_tools([
+        get_report_detail,
+        get_survey_data,
+        get_dimension_scores,
+    ])
+
+    builder = StateGraph(AnalysisState)
+
+    async def gather_data(state: AnalysisState) -> dict:
+        """收集报告 + 问卷 + 维度数据"""
+        result = {}
+        if state.get("report_id"):
+            try:
+                detail = await get_report_detail.ainvoke({"report_id": state["report_id"]})
+                result["report_data"] = detail
+            except Exception as e:
+                logger.warning("获取报告详情失败: %s", e)
+            try:
+                survey = await get_survey_data.ainvoke({"report_id": state["report_id"]})
+                result["survey_data"] = survey
+            except Exception as e:
+                logger.warning("获取问卷数据失败: %s", e)
+        return result
+
+    async def analyze(state: AnalysisState) -> dict:
+        """LLM 分析"""
+        context_parts = []
+        if state.get("report_data"):
+            context_parts.append(f"报告数据: {state['report_data']}")
+        if state.get("survey_data"):
+            context_parts.append(f"问卷数据: {state['survey_data']}")
+        if state.get("focus"):
+            context_parts.append(f"重点关注: {state['focus']}")
+
+        context_text = "\n".join(context_parts) if context_parts else "暂无数据"
+
+        messages = [
+            SystemMessage(content=await get_prompt("analysis") or ANALYSIS_SYSTEM_PROMPT),
+            SystemMessage(content=f"待分析数据:\n{context_text}"),
+            HumanMessage(content="请分析以上健康数据, 给出评估和建议。"),
+        ]
+
+        response = await llm_with_tools.ainvoke(messages)
+        return {"analysis": response.content}
+
+    builder.add_node("gather_data", gather_data)
+    builder.add_node("analyze", analyze)
+
+    builder.add_edge(START, "gather_data")
+    builder.add_edge("gather_data", "analyze")
+    builder.add_edge("analyze", END)
+
+    checkpointer = MemorySaver()
+    return builder.compile(checkpointer=checkpointer)

+ 58 - 0
cfc-langgraph/app/graphs/article_quiz_graph.py

@@ -0,0 +1,58 @@
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.config import settings
+from app.monitoring import monitor_agent
+from app.prompt_service import get_prompt
+import json
+import logging
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一位家庭教育出题助手。根据给定的文章内容,为读者生成 3 道单项选择题。
+
+要求:
+1. 每题 4 个选项,选项以 "A. "、"B. "、"C. "、"D. " 开头
+2. 题目考察文章核心内容的理解,适合青少年读者
+3. 每题标注所属五维(body/mind/wisdom/action/wealth),缺省为 wisdom
+4. 以 JSON 数组格式返回,不要返回其他文字,只返回 JSON 数组
+
+输出格式:
+[
+  {"question": "问题", "options": ["A. xxx", "B. xxx", "C. xxx", "D. xxx"], "answer": "A", "dimension": "wisdom", "explanation": "解析"}
+]
+"""
+
+
+class ArticleQuizAgent:
+    def __init__(self):
+        self.llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=settings.llm_temperature,
+        )
+
+    @monitor_agent("article_quiz")
+    async def run(self, article_title: str, article_content: str, profile_summary: str = "") -> dict:
+        """根据文章内容生成 3 道选择题,失败返回空 questions"""
+        try:
+            human = f"文章标题:{article_title}\n文章内容:{article_content}"
+            if profile_summary:
+                human += f"\n用户画像摘要:{profile_summary}"
+            messages = [
+                SystemMessage(content=await get_prompt("article_quiz") or SYSTEM_PROMPT),
+                HumanMessage(content=human),
+            ]
+            response = await self.llm.ainvoke(messages)
+            content = response.content.strip()
+            if "```json" in content:
+                content = content.split("```json")[1].split("```")[0].strip()
+            elif "```" in content:
+                content = content.split("```")[1].split("```")[0].strip()
+            questions = json.loads(content)
+            if not isinstance(questions, list):
+                return {"questions": [], "fallback_used": True}
+            return {"questions": questions, "fallback_used": False}
+        except Exception as e:
+            logger.warning("文章出题生成失败: %s", e)
+            return {"questions": [], "fallback_used": True}

+ 227 - 0
cfc-langgraph/app/graphs/chat_graph.py

@@ -0,0 +1,227 @@
+from typing import TypedDict, Literal
+from langgraph.graph import StateGraph, START, END
+from app.checkpointer import get_checkpointer
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.agents.intent_classifier import IntentClassifier, Intent
+from app.agents.chat_agent import ChatAgent
+from app.tools.product_tools import (
+    search_product_by_keyword,
+    search_article_by_keyword,
+    search_activity_by_keyword,
+)
+from app.memory.store import MemoryManager
+from app.config import settings
+from app.prompt_service import get_prompt
+from app.portrait_service import get_user_portrait_text
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class ChatState(TypedDict):
+    query: str
+    user_id: int
+    conversation_id: str
+    child_id: int | None
+    intent: Intent | None
+    context: dict | None
+    self_check_result: str | None  # P1-2: 自检结果 JSON
+    messages: list | None
+    answer: str | None
+    tasks: list[dict]
+    sources: list[dict]
+
+
+DEFAULT_CHAT_PROMPT = """你是一个儿童成长家庭助手, 回答关于孩子成长、健康、教育的各种问题。
+
+你可以使用搜索工具查找商品、活动和文章来辅助回答。
+
+回答原则:
+1. 用中文, 语气温暖亲切
+2. 如果用户提到具体孩子, 参考提供的家庭上下文
+3. 需要推荐时使用搜索工具
+4. 可以生成 [TASK: {"title": "任务名", "dimension": "身/心/智/行/富", "points": 10}] 标记来创建行动任务
+5. 不要编造医疗建议, 严重问题建议咨询医生
+"""
+
+
+def create_chat_graph():
+    """创建聊天 StateGraph"""
+    agent = ChatAgent()
+    classifier = IntentClassifier()
+
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=settings.llm_temperature,
+    )
+    
+    # 初始化嵌入模型用于记忆存储
+    from app.rag.embeddings import get_embeddings
+    embeddings = get_embeddings()
+    memory_mgr = MemoryManager(embeddings)
+    java = JavaClient()
+
+    llm_with_tools = llm.bind_tools([
+        search_product_by_keyword,
+        search_article_by_keyword,
+        search_activity_by_keyword,
+    ])
+
+    builder = StateGraph(ChatState)
+
+    # ── 节点 ──
+
+    async def classify_intent(state: ChatState) -> dict:
+        intent = await classifier.classify(
+            state["query"],
+            context=str(state.get("context", {})),
+        )
+        return {"intent": intent}
+
+    async def load_context(state: ChatState) -> dict:
+        ctx = await agent.load_context(state["user_id"], state.get("child_id"))
+        return {"context": ctx}
+
+    async def llm_call(state: ChatState) -> dict:
+        """核心 LLM 调用 + Tool"""
+        chat_prompt = await get_prompt("chat_assistant") or DEFAULT_CHAT_PROMPT
+        messages = [SystemMessage(content=chat_prompt)]
+
+        # 画像注入
+        member_id = state.get("child_id")
+        portrait_text = await get_user_portrait_text(java, state["user_id"], member_id)
+        if portrait_text:
+            messages.insert(1, SystemMessage(content=portrait_text))
+
+        # P1-2: 自检结果注入(如有)
+        self_check_result = state.get("self_check_result")
+        if self_check_result:
+            try:
+                import json as _json
+                sc = _json.loads(self_check_result)
+                sc_text = f"用户最近一次五维自检结果:\n总分 {sc.get('totalScore', 0)}/45,"
+                dims = sc.get('dimensions') or sc.get('scores') or {}
+                if isinstance(dims, list):
+                    dim_lines = [f"{d.get('name','')}: {d.get('score',0)}分" for d in dims]
+                elif isinstance(dims, dict):
+                    dim_lines = [f"{k}: {v}分" for k, v in dims.items()]
+                else:
+                    dim_lines = [str(dims)]
+                sc_text += " | ".join(dim_lines)
+                insight = sc.get('familyInsight') or sc.get('aiInsight')
+                if insight:
+                    sc_text += f"\nAI 洞察: {insight}"
+                messages.insert(1, SystemMessage(content=sc_text))
+            except Exception as _e:
+                logger.warning("解析 self_check_result 失败: %s", _e)
+
+        # 注入家庭上下文 + 用户健康现状
+        ctx = state.get("context", {})
+        if isinstance(ctx, dict):
+            ctx_parts = []
+            if ctx.get("child_id") is not None:
+                ctx_parts.append(f"child_id: {ctx['child_id']}")
+            if ctx.get("report_id") is not None:
+                ctx_parts.append(f"report_id: {ctx['report_id']}")
+            if ctx.get("family_id") is not None:
+                ctx_parts.append(f"family_id: {ctx['family_id']}")
+            if ctx.get("health_status"):
+                ctx_parts.append(f"用户健康现状: {ctx['health_status']}")
+            if ctx.get("diet_preferences"):
+                ctx_parts.append(f"用户饮食偏好: {ctx['diet_preferences']}")
+            if ctx_parts:
+                messages.append(SystemMessage(content="\n家庭上下文:\n" + "\n".join(ctx_parts)))
+
+        # 注入长期记忆
+        try:
+            memories = await memory_mgr.recall(state["user_id"], state["query"])
+            if memories:
+                mem_text = "\n".join([f"- {m}" for m in memories])
+                messages.append(SystemMessage(
+                    content=f"相关历史对话:\n{mem_text}"
+                ))
+        except Exception as e:
+            logger.warning("召回记忆失败: %s", e)
+
+        # 用户消息
+        messages.append(HumanMessage(content=state["query"]))
+
+        response = await llm_with_tools.ainvoke(messages)
+        answer = response.content
+
+        # B-117 兜底:部分网关/模型在 bind_tools 下偶发返回空 content(finish_reason
+        # 为 tool_calls 但未携带可用 tool_call,或直接空文本)。此时改用无 tools 的 llm
+        # 重试一次,避免 auto-tag 等纯文本任务拿到空 answer。
+        if not answer and not response.response_metadata.get("tool_calls"):
+            logger.warning("bind_tools 调用返回空 content,改用无工具 llm 重试")
+            response = await llm.ainvoke(messages)
+            answer = response.content
+
+        # 提取任务
+        tasks = await agent.extract_tasks(answer, state["user_id"], state["conversation_id"])
+
+        # 提取来源
+        sources = []
+        if response.response_metadata.get("tool_calls"):
+            for tc in response.response_metadata["tool_calls"]:
+                sources.append({
+                    "type": "tool",
+                    "name": tc.get("name", ""),
+                    "input": tc.get("args", {}),
+                })
+
+        return {
+            "answer": answer,
+            "tasks": tasks,
+            "sources": sources,
+            "messages": [{"role": "user", "content": state["query"]},
+                         {"role": "assistant", "content": answer}],
+        }
+
+    async def save_memory(state: ChatState) -> dict:
+        """对话后保存到长期记忆"""
+        try:
+            if state.get("messages"):
+                await memory_mgr.save_conversation(
+                    state["user_id"],
+                    state["conversation_id"],
+                    state["messages"],
+                )
+        except Exception as e:
+            logger.warning("保存记忆失败: %s", e)
+        return {}
+
+    # ── 路由 ──
+
+    def route_by_intent(state: ChatState) -> Literal["llm_call", END]:
+        if state["intent"] in (
+            Intent.RECOMMEND,
+            Intent.ANALYSIS,
+            Intent.HEALTH,
+        ):
+            # 这些意图需要更专业的 Agent (Phase 3 实现)
+            # 当前先走通用 LLM
+            pass
+        return "llm_call"
+
+    # ── 构建图 ──
+
+    builder.add_node("classify_intent", classify_intent)
+    builder.add_node("load_context", load_context)
+    builder.add_node("llm_call", llm_call)
+    builder.add_node("save_memory", save_memory)
+
+    builder.add_edge(START, "classify_intent")
+    builder.add_edge("classify_intent", "load_context")
+    builder.add_conditional_edges("load_context", route_by_intent)
+    builder.add_edge("llm_call", "save_memory")
+    builder.add_edge("save_memory", END)
+
+    checkpointer = get_checkpointer()
+    graph = builder.compile(checkpointer=checkpointer)
+
+    return graph

+ 327 - 0
cfc-langgraph/app/graphs/health_butler_graph.py

@@ -0,0 +1,327 @@
+from typing import TypedDict, Optional, Literal
+from langgraph.graph import StateGraph, START, END
+from langgraph.checkpoint.memory import MemorySaver
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.tools.java_client import JavaClient
+from app.tools.product_tools import (
+    search_product_by_keyword,
+    search_article_by_keyword,
+)
+from app.memory.store import MemoryManager
+from app.config import settings
+from app.prompt_service import get_prompt
+from app.portrait_service import get_user_portrait_text
+import logging
+import json
+
+logger = logging.getLogger(__name__)
+
+
+class HealthButlerState(TypedDict):
+    query: str
+    user_id: int
+    conversation_id: str
+    family_id: int | None
+    child_id: int | None
+    report_id: int | None
+    focus: str | None          # gut / nutrition / overall / chronic
+    kb_context: dict | None
+    knowledge_results: list[dict]
+    answer: str | None
+    tasks: list[dict]
+    sources: list[dict]
+    messages: list | None
+
+
+DEFAULT_BUTLER_PROMPT = """你是一个家庭AI健康管家, 为用户提供专业、温暖的个性化健康建议。
+
+你的能力:
+1. 基于健康知识库(菌属功能、指标解读、营养素、食物)提供科学建议
+2. 解读健康报告数据, 结合知识库给出改善方案
+3. 根据菌群检测结果推荐精准营养方案
+4. 提供可执行的健康微行动
+
+回答原则:
+1. 用中文, 像家庭医生一样亲切但专业
+2. 引用知识库中的菌属/指标/食物信息作为证据
+3. 优先使用知识库数据, 其次使用通用健康知识
+4. 需要产品推荐时使用搜索工具
+5. 生成 [TASK: {"title": "任务名", "dimension": "身", "points": 10, "frequency": "每天"}] 标记创建健康行动任务
+6. 超出知识库范围的慢性病/急症问题, 建议咨询专业医生
+7. 不要编造医学建议, 不夸大效果
+"""
+
+
+def create_health_butler_graph():
+    """创建 AI 健康管家 StateGraph — 知识检索 + LLM 建议 + 记忆"""
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=settings.llm_temperature,
+    )
+
+    from app.rag.embeddings import get_embeddings
+    embeddings = get_embeddings()
+    memory_mgr = MemoryManager(embeddings)
+
+    java = JavaClient()
+
+    llm_with_tools = llm.bind_tools([
+        search_product_by_keyword,
+        search_article_by_keyword,
+    ])
+
+    builder = StateGraph(HealthButlerState)
+
+    async def load_knowledge(state: HealthButlerState) -> dict:
+        """阶段1: 从 Java 后端加载健康知识库上下文"""
+        context = {}
+        try:
+            client = await java._get_client()
+            resp = await client.post(
+                "/api/health/knowledge/list",
+                json={},
+            )
+            data = resp.json()
+            if data.get("code") == 200:
+                items = data.get("data", [])
+                # 按 itemType 分组
+                by_type = {}
+                for item in items:
+                    t = item.get("itemType", "unknown")
+                    if t not in by_type:
+                        by_type[t] = []
+                    by_type[t].append(item)
+                context["kb_items"] = len(items)
+                context["kb_by_type"] = {k: len(v) for k, v in by_type.items()}
+                context["kb_loaded"] = True
+            else:
+                context["kb_loaded"] = False
+        except Exception as e:
+            logger.warning("加载健康知识库失败: %s", e)
+            context["kb_loaded"] = False
+
+        return {"kb_context": context}
+
+    async def search_knowledge(state: HealthButlerState) -> dict:
+        """阶段2: 根据 query 意图精准搜索知识库"""
+        query = state["query"]
+        results = []
+
+        # 提取 query 中可能的菌属名/指标名/食物名关键词
+        # 策略: 对 query 做简单的关键词匹配, 调用 Java 知识库逐个查询
+        keywords = _extract_health_keywords(query)
+        if keywords:
+            client = await java._get_client()
+            for kw in keywords[:5]:  # 最多查询5个关键词
+                # 优先查 bacteria 类型
+                for item_type in ["bacteria", "indicator", "food", "nutrient"]:
+                    try:
+                        resp = await client.post(
+                            "/api/health/knowledge/query",
+                            json={"itemType": item_type, "itemName": kw},
+                        )
+                        data = resp.json()
+                        if data.get("code") == 200 and data.get("data"):
+                            results.append({
+                                "type": item_type,
+                                "keyword": kw,
+                                "data": data["data"],
+                            })
+                            break  # 命中即跳出
+                    except Exception:
+                        continue
+
+        return {"knowledge_results": results}
+
+    async def llm_answer(state: HealthButlerState) -> dict:
+        """阶段3: LLM 生成个性化健康建议"""
+        messages = [SystemMessage(content=await get_prompt("health_butler") or DEFAULT_BUTLER_PROMPT)]
+
+        # 画像注入
+        member_id = state.get("child_id")
+        portrait_text = await get_user_portrait_text(java, state["user_id"], member_id)
+        if portrait_text:
+            messages.insert(1, SystemMessage(content=portrait_text))
+
+        # 注入健康知识库上下文
+        kb_ctx = state.get("kb_context", {})
+        knowledge_results = state.get("knowledge_results", [])
+        if knowledge_results:
+            kb_text_parts = []
+            for r in knowledge_results:
+                d = r.get("data", {})
+                name = d.get("itemName", r.get("keyword", ""))
+                cat = d.get("category", "")
+                desc = d.get("description", "")
+                suggestion = d.get("suggestion", "")
+                normal_range = d.get("normalRange", "")
+
+                parts = [f"【{r['type']}】{name}"]
+                if cat:
+                    parts.append(f"(分类: {cat})")
+                if normal_range:
+                    parts.append(f"正常范围: {normal_range}")
+                if desc:
+                    parts.append(f"{desc}")
+                if suggestion:
+                    parts.append(f"建议: {suggestion}")
+                kb_text_parts.append(" ".join(parts))
+
+            kb_text = "\n---\n".join(kb_text_parts)
+            messages.append(SystemMessage(content=f"健康知识库参考:\n{kb_text}"))
+
+        # 注入家庭上下文
+        family_id = state.get("family_id")
+        if family_id:
+            try:
+                client = await java._get_client()
+                resp = await client.post(
+                    "/api/ai/context",
+                    json={
+                        "user_id": str(state["user_id"]),
+                        "params": {
+                            "familyId": family_id,
+                            **({"childId": state["child_id"]} if state.get("child_id") else {}),
+                        },
+                    },
+                )
+                data = resp.json()
+                if data.get("code") == 200:
+                    ctx = data.get("data", {})
+                    if ctx:
+                        messages.append(SystemMessage(content=f"家庭上下文:\n{json.dumps(ctx, ensure_ascii=False, indent=2)}"))
+            except Exception as e:
+                logger.debug("加载家庭上下文跳过: %s", e)
+
+        # 注入长期记忆
+        try:
+            memories = await memory_mgr.recall(state["user_id"], state["query"])
+            if memories:
+                mem_text = "\n".join([f"- {m}" for m in memories])
+                messages.append(SystemMessage(content=f"相关历史对话:\n{mem_text}"))
+        except Exception as e:
+            logger.warning("召回记忆失败: %s", e)
+
+        # 用户消息
+        focus = state.get("focus")
+        query = state["query"]
+        if focus:
+            query = f"[重点关注: {focus}] {query}"
+        messages.append(HumanMessage(content=query))
+
+        response = await llm_with_tools.ainvoke(messages)
+        answer = response.content
+
+        # 提取任务
+        import re
+        tasks = []
+        pattern = r'\[TASK:\s*\{([^}]+)\}\]'
+        for match in re.findall(pattern, answer):
+            task_info = {}
+            for kv in match.split(","):
+                if ":" in kv:
+                    k, v = kv.split(":", 1)
+                    task_info[k.strip()] = v.strip().strip('"').strip("'")
+            if task_info.get("title"):
+                tasks.append(task_info)
+
+        sources = []
+        for r in knowledge_results:
+            d = r.get("data", {})
+            sources.append({
+                "type": "health_kb",
+                "name": d.get("itemName", r.get("keyword", "")),
+                "category": d.get("category", ""),
+            })
+        if response.response_metadata.get("tool_calls"):
+            for tc in response.response_metadata["tool_calls"]:
+                sources.append({
+                    "type": "tool",
+                    "name": tc.get("name", ""),
+                })
+
+        return {
+            "answer": answer,
+            "tasks": tasks,
+            "sources": sources,
+            "messages": [
+                {"role": "user", "content": state["query"]},
+                {"role": "assistant", "content": answer},
+            ],
+        }
+
+    async def save_memory(state: HealthButlerState) -> dict:
+        try:
+            if state.get("messages"):
+                await memory_mgr.save_conversation(
+                    state["user_id"],
+                    state["conversation_id"],
+                    state["messages"],
+                )
+        except Exception as e:
+            logger.warning("保存记忆失败: %s", e)
+        return {}
+
+    # ── 路由 ──
+
+    def route_after_knowledge(state: HealthButlerState) -> Literal["search_knowledge", "llm_answer"]:
+        kb_ctx = state.get("kb_context", {})
+        if kb_ctx.get("kb_loaded"):
+            return "search_knowledge"
+        return "llm_answer"
+
+    # ── 构建图 ──
+
+    builder.add_node("load_knowledge", load_knowledge)
+    builder.add_node("search_knowledge", search_knowledge)
+    builder.add_node("llm_answer", llm_answer)
+    builder.add_node("save_memory", save_memory)
+
+    builder.add_edge(START, "load_knowledge")
+    builder.add_conditional_edges("load_knowledge", route_after_knowledge)
+    builder.add_edge("search_knowledge", "llm_answer")
+    builder.add_edge("llm_answer", "save_memory")
+    builder.add_edge("save_memory", END)
+
+    checkpointer = MemorySaver()
+    graph = builder.compile(checkpointer=checkpointer)
+
+    return graph
+
+
+def _extract_health_keywords(query: str) -> list[str]:
+    """从 query 中提取健康相关关键词(菌属、指标、食物等名词)"""
+    # 简单策略: 提取2字以上的中文词作为候选
+    import re
+    # 提取中文字符组成的连续词段
+    chinese_words = re.findall(r'[\u4e00-\u9fff]{2,}', query)
+    # 提取英文/拉丁名词组
+    english_words = re.findall(r'[A-Za-z][A-Za-z\s]{2,20}[A-Za-z]', query)
+
+    keywords = []
+    # 过滤常见通用词
+    stopwords = {"请问", "帮我", "能不能", "可不可以", "怎么样", "为什么",
+                 "是什么", "怎么办", "什么意思", "好不好", "是否", "你好",
+                 "谢谢", "请", "我想", "需要", "关于", "一个", "这个",
+                 "那个", "哪些", "什么", "怎么", "如何", "多少", "是不是"}
+    for w in chinese_words:
+        if w not in stopwords and len(w) >= 2:
+            keywords.append(w)
+
+    for w in english_words:
+        w = w.strip()
+        if len(w) > 2:
+            keywords.append(w)
+
+    # 去重 + 限数量
+    seen = set()
+    deduped = []
+    for kw in keywords:
+        if kw not in seen:
+            seen.add(kw)
+            deduped.append(kw)
+
+    return deduped[:10]

+ 193 - 0
cfc-langgraph/app/graphs/health_coach_graph.py

@@ -0,0 +1,193 @@
+"""
+AI 健康教练 LangGraph - 专为儿童健康咨询设计的对话图
+Uses RAG retrieval from health knowledge base.
+"""
+from typing import TypedDict
+from langgraph.graph import StateGraph, START, END
+from app.checkpointer import get_checkpointer
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.rag.retriever import RagRetriever
+from app.memory.store import MemoryManager
+from app.config import settings
+from app.prompt_service import get_prompt
+from app.portrait_service import get_user_portrait_text
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class HealthCoachState(TypedDict):
+    query: str
+    user_id: int
+    child_id: int | None
+    conversation_id: str | None
+    context: dict | None
+    answer: str | None
+    sources: list[dict]
+    memory_messages: list | None
+
+
+DEFAULT_COACH_PROMPT = """你是一个儿童健康教练,喜欢用提问的方式引导家长发现问题和解决方案。
+
+核心原则:
+1. 先问后答:不要直接给答案,用问题引导家长思考
+   - "孩子这种情况多久了?"、"平时饮食习惯是怎样的?"、"体重身高发育曲线有没有记录?"
+2. 用开放式问题了解情况,再给针对性建议
+3. 语气温暖,像一个耐心的教练在陪伴家长成长
+
+你的职责:
+1. 儿童体质调理(如挑食、瘦弱、易疲劳、反复生病)—— 用提问了解情况
+2. 科学喂养和营养建议 —— 先问饮食现状再给建议
+3. 日常保健(睡眠、运动、季节防护)—— 引导家长发现生活中的问题
+4. 体质辨识基础咨询 —— 通过提问帮助家长理解孩子体质特点
+5. 健康问题判断 —— 先收集症状信息再建议是否就医
+
+回答结构(教练风格):
+1. 提问:先问1-2个关键问题了解情况
+2. 分析:简短总结你观察到的问题
+3. 建议:给出2-3个可操作的建议
+4. 跟进问句:留一个后续跟进的问题,体现教练陪伴感
+
+原则:
+- 涉及严重症状(急性腹痛、高烧不退、严重外伤等)立刻建议就医,不提问
+- 不确定时明确说"建议咨询专业医生"
+- 始终用中文回答
+"""
+
+
+def create_health_coach_graph():
+    """创建AI健康教练 StateGraph"""
+    # LLM
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=settings.llm_temperature,
+    )
+
+    # 嵌入和检索
+    from app.rag.embeddings import get_embeddings
+    embeddings = get_embeddings()
+    retriever = RagRetriever(collection_name="health_knowledge")
+    memory_mgr = MemoryManager(embeddings)
+    java = JavaClient()
+
+    # 带工具的 LLM(健康知识库检索)
+    async def health_retrieve(query: str, user_id: int) -> list[dict]:
+        try:
+            results = await retriever.retrieve(
+                query,
+                filters={"user_id": user_id},
+                k=3,
+            )
+            return results
+        except Exception as e:
+            logger.warning("健康知识检索失败: %s", e)
+            return []
+
+    async def generate_answer(state: HealthCoachState) -> dict:
+        """带健康知识检索的 LLM 生成"""
+        # 人格路由:context.coach_id (xibao/fubao) -> 专属prompt,三级回退保证可用性
+        _ctx = state.get("context") or {}
+        _coach_id = _ctx.get("coach_id")
+        if _coach_id not in ("xibao", "fubao"):
+            _coach_id = None
+        _persona_prompt = await get_prompt(f"health_coach_{_coach_id}") if _coach_id else None
+        _base_prompt = await get_prompt("health_coach")
+        messages = [SystemMessage(content=_persona_prompt or _base_prompt or DEFAULT_COACH_PROMPT)]
+
+        # 画像注入
+        member_id = _ctx.get("child_id")
+        portrait_text = await get_user_portrait_text(java, state["user_id"], member_id)
+        if portrait_text:
+            messages.insert(1, SystemMessage(content=portrait_text))
+
+        # 家庭上下文
+        ctx = state.get("context") or {}
+        if ctx:
+            child_info = []
+            if ctx.get("child_id"):
+                child_info.append(f"孩子ID: {ctx['child_id']}")
+            if ctx.get("family_id"):
+                child_info.append(f"家庭ID: {ctx['family_id']}")
+            if child_info:
+                messages.append(SystemMessage(
+                    content="用户背景信息: " + ", ".join(child_info)
+                ))
+
+        # 健康知识检索
+        retrieved = await health_retrieve(state["query"], state["user_id"])
+        sources = []
+        if retrieved:
+            context_texts = []
+            for i, r in enumerate(retrieved[:3]):
+                src = r.get("metadata", {})
+                title = src.get("title", "健康知识")
+                content = r["content"][:300]
+                context_texts.append(f"[{i+1}] {title}:\n{content}")
+                sources.append({
+                    "type": "knowledge",
+                    "title": title,
+                    "content": content,
+                })
+            knowledge_context = "\n\n---\n".join(context_texts)
+            messages.append(SystemMessage(
+                content=f"以下是与问题相关的健康知识参考:\n{knowledge_context}"
+            ))
+
+        # 长期记忆
+        try:
+            memories = await memory_mgr.recall(state["user_id"], state["query"])
+            if memories:
+                mem_text = "\n".join([f"- {m}" for m in memories[:3]])
+                messages.append(SystemMessage(
+                    content=f"该用户的历史健康咨询记录:\n{mem_text}"
+                ))
+        except Exception as e:
+            logger.warning("召回健康记忆失败: %s", e)
+
+        # 用户问题
+        messages.append(HumanMessage(content=state["query"]))
+
+        response = await llm.ainvoke(messages)
+        answer = response.content
+
+        return {
+            "answer": answer,
+            "sources": sources,
+            "memory_messages": [
+                {"role": "user", "content": state["query"]},
+                {"role": "assistant", "content": answer},
+            ],
+        }
+
+    async def save_memory(state: HealthCoachState) -> dict:
+        """保存对话到长期记忆"""
+        try:
+            if state.get("memory_messages"):
+                await memory_mgr.save_conversation(
+                    state["user_id"],
+                    state.get("conversation_id") or f"health_{state['user_id']}",
+                    state["memory_messages"],
+                )
+        except Exception as e:
+            logger.warning("保存健康教练记忆失败: %s", e)
+        return {}
+
+    # ── 构建图 ──
+
+    builder = StateGraph(HealthCoachState)
+
+    builder.add_node("generate_answer", generate_answer)
+    builder.add_node("save_memory", save_memory)
+
+    builder.add_edge(START, "generate_answer")
+    builder.add_edge("generate_answer", "save_memory")
+    builder.add_edge("save_memory", END)
+
+    checkpointer = get_checkpointer()
+    graph = builder.compile(checkpointer=checkpointer)
+
+    return graph

+ 361 - 0
cfc-langgraph/app/graphs/health_plan_graph.py

@@ -0,0 +1,361 @@
+"""
+健康方案生成 LangGraph - 分步骤结构化方案生成
+
+工作流:
+1. 数据收集: 家庭成员信息 + 健康指标 + 知识库检索
+2. LLM 生成: 总览概述 + 营养/饮食/运动 三个 section
+3. 返回结构化 JSON
+
+每次调用 LLM 时遵循统一的数据组装方式:
+  - 用户指标 (来自 Java context API)
+  - 知识库参考 (RAG 检索)
+  - 系统提示词 (带输出格式模板)
+"""
+from typing import TypedDict, Literal
+from langgraph.graph import StateGraph, START, END
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.rag.retriever import RagRetriever
+from app.config import settings
+from app.tools.java_client import JavaClient
+from app.prompt_service import get_prompt
+import logging
+
+logger = logging.getLogger(__name__)
+
+SECTION_KEYS = ["nutrition", "diet", "exercise"]
+
+DEFAULT_PROMPT = """你是一个专业的家庭健康方案规划师。根据用户的健康数据和目标,生成结构化的改善方案。
+
+## 输出格式(必须严格遵守 JSON)
+
+```json
+{
+  "overview": "总体概述(100字以内,说明方案目标和核心策略)",
+  "sections": [
+    {
+      "key": "nutrition",
+      "title": "营养补充建议",
+      "content": "Markdown 格式的详细内容,包含具体产品推荐、用量、服用时间",
+      "items": [
+        {"name": "产品名", "dosage": "用量", "timing": "服用时间", "reason": "推荐理由"}
+      ]
+    },
+    {
+      "key": "diet", 
+      "title": "饮食建议",
+      "content": "Markdown 格式的餐饮建议,包含早餐/午餐/晚餐建议",
+      "items": [{"meal": "餐型", "food": "食物建议", "notes": "注意事项"}]
+    },
+    {
+      "key": "exercise",
+      "title": "运动计划",
+      "content": "Markdown 格式的运动建议,包含频率、时长、类型",
+      "items": [{"type": "运动类型", "duration": "时长", "frequency": "频率", "notes": "注意事项"}]
+    }
+  ]
+}
+```
+
+## 原则
+1. 基于实际数据给出建议,不编造
+2. 引用知识库时标注来源
+3. 建议要具体可执行,避免空泛
+4. 营养补充部分要具体到品牌/产品类型和用量
+5. 严重健康问题建议咨询医生
+"""
+
+REGENERATE_SECTION_PROMPT = """你是一个家庭健康方案规划师。根据用户反馈重新生成指定部分的内容。
+
+## 当前方案内容
+{existing_section_content}
+
+## 用户反馈
+{feedback}
+
+## 相关背景数据
+{context_summary}
+
+请重新生成该部分内容,保持与原格式一致。只输出新的 content 字段值(Markdown 格式),不需要输出 JSON 结构。"""
+
+
+class PlanState(TypedDict):
+    member_ids: str
+    dimensions: str
+    goal: str
+    family_id: int
+    members_info: dict
+    indicators: list
+    abnormal_indicators: list
+    indicator_changes: list
+    kb_results: list
+    overview: str
+    nutrition_section: str
+    diet_section: str
+    exercise_section: str
+    full_response: dict
+    error: str
+
+
+async def collect_data(state: PlanState) -> dict:
+    """Step 1: 收集用户数据 + 知识库检索"""
+    java = JavaClient()
+    retriever = RagRetriever(collection_name="cfc_knowledge")
+
+    member_ids_str = state.get("member_ids", "")
+    member_ids = [m.strip() for m in member_ids_str.split(",") if m.strip()]
+    goal = state.get("goal", "")
+    dimensions = state.get("dimensions", "") or ""
+
+    # 1a. 获取家庭成员信息
+    members_info = []
+    for uid_str in member_ids:
+        ctx = await java.get_family_context(int(uid_str), "child_info")
+        children = ctx.get("children", []) if isinstance(ctx, dict) else []
+        for child in children:
+            cid = str(child.get("用户ID", ""))
+            if cid == uid_str:
+                members_info.append({
+                    "id": cid,
+                    "name": child.get("姓名", f"成员{cid}"),
+                    "age": child.get("年龄", "未知"),
+                    "energy": child.get("能量", 0),
+                })
+                break
+        if not any(m["id"] == uid_str for m in members_info):
+            members_info.append({"id": uid_str, "name": f"成员{uid_str}", "age": "未知", "energy": 0})
+
+    # 1b. 获取健康指标
+    all_indicators = []
+    abnormal_list = []
+    indicator_changes = []  # 成员指标"当前值 vs 上次"变化 (来自 member_indicator_current)
+    for member in members_info:
+        reports = await java.get_member_reports(int(member["id"]))
+        if not reports:
+            continue
+        latest = max(reports, key=lambda r: r.get("reportDate", ""))
+        report_id = latest.get("id")
+        indicators = await java.get_report_indicators(report_id)
+        for ind in indicators:
+            ind["_member_id"] = member["id"]
+            ind["_member_name"] = member["name"]
+            all_indicators.append(ind)
+
+        # 拉取指标变化 (delta/trend), 即使无报告也可能有历史指标
+        cur_list = await java.get_member_indicator_current(int(member["id"]))
+        for cur in cur_list:
+            delta = cur.get("delta")
+            trend = cur.get("trend", "")
+            if delta is not None and trend in ("up", "down"):
+                indicator_changes.append({
+                    "member": member["name"],
+                    "member_id": member["id"],
+                    "indicator": cur.get("name", ""),
+                    "current": cur.get("value", ""),
+                    "previous": cur.get("previousValue", ""),
+                    "delta": delta,
+                    "trend": trend,
+                })
+
+    # 1c. 识别异常指标
+    known_indicators = {}
+    for ind in all_indicators:
+        name = ind.get("indicatorName", "").strip()
+        if not name or name in known_indicators:
+            continue
+        for itype in ["indicator", "bacteria", "nutrient"]:
+            kb = await java.query_health_knowledge(itype, name)
+            if kb:
+                known_indicators[name] = kb
+                break
+
+    for ind in all_indicators:
+        name = ind.get("indicatorName", "")
+        status = ind.get("status", "")
+        kb = known_indicators.get(name, {})
+        entry = {
+            "member": ind.get("_member_name", ""),
+            "indicator": name,
+            "value": ind.get("indicatorValue", ""),
+            "unit": ind.get("unit", ""),
+            "ref_range": kb.get("normalRange", ind.get("refRange", "")),
+            "description": kb.get("description", ""),
+            "suggestion": kb.get("suggestion", ""),
+        }
+        if status in ("abnormal", "high", "low", "偏高", "偏低"):
+            abnormal_list.append(entry)
+
+    # 1c-2. 把"指标变化(delta 较大)"也视为值得关注的变化点, 并入 abnormal_list
+    _change_seen = set()
+    for ch in indicator_changes:
+        key = (ch["member"], ch["indicator"])
+        if key in _change_seen:
+            continue
+        _change_seen.add(key)
+        try:
+            d = float(ch["delta"])
+        except (TypeError, ValueError):
+            continue
+        if abs(d) >= 10:  # 显著变化阈值 (按指标量级可调)
+            arrow = "上升" if d > 0 else "下降"
+            abnormal_list.append({
+                "member": ch["member"],
+                "indicator": ch["indicator"],
+                "value": str(ch.get("current", "")),
+                "unit": "",
+                "ref_range": "上次: %s" % ch.get("previous", ""),
+                "description": "指标较上次%s %.1f (当前 %.1f, 上次 %s)" % (
+                    arrow, abs(d), float(ch["current"]) if ch.get("current") is not None else -1, ch.get("previous", "")),
+                "suggestion": "该指标近期%s明显, 方案中应体现针对性调整" % arrow,
+                "_is_change": True,
+            })
+
+    # 1d. 知识库检索
+    kb_results = []
+    queries = set()
+    for ind in abnormal_list:
+        queries.add(ind["indicator"])
+    queries.add(goal)
+    if dimensions:
+        queries.add(dimensions)
+    for q in list(queries)[:8]:
+        results = await retriever.retrieve(q, k=3)
+        kb_results.extend(results)
+
+    return {
+        "members_info": members_info,
+        "indicators": all_indicators,
+        "abnormal_indicators": abnormal_list,
+        "indicator_changes": indicator_changes,
+        "kb_results": kb_results,
+    }
+
+
+async def build_prompt(state: PlanState) -> str:
+    """组装 LLM prompt"""
+    base_prompt = await get_prompt("health_plan") or DEFAULT_PROMPT
+    parts = [base_prompt]
+
+    parts.append(f"\n## 用户目标\n{state['goal']}")
+    if state.get("dimensions"):
+        parts.append(f"\n## 重点关注维度\n{state['dimensions']}")
+
+    parts.append("\n## 家庭成员")
+    for m in state["members_info"]:
+        parts.append(f"- {m['name']} (年龄: {m['age']})")
+
+    if state["abnormal_indicators"]:
+        parts.append("\n## 异常指标")
+        for ind in state["abnormal_indicators"][:8]:
+            parts.append(
+                f"- {ind['member']} - {ind['indicator']}: {ind['value']}{ind.get('unit','')} "
+                f"(参考: {ind['ref_range']})"
+            )
+            if ind.get("description"):
+                parts.append(f"  说明: {ind['description']}")
+
+    if state.get("indicator_changes"):
+        parts.append("\n## 指标较上次报告的变化(方案必须考虑这些趋势)")
+        for ch in state["indicator_changes"][:12]:
+            arrow = "上升" if ch.get("trend") == "up" else "下降"
+            parts.append(
+                f"- {ch[member]} - {ch[indicator]}: {ch.get(current,)} "
+                f"(上次: {ch.get(previous,)}, {arrow} {abs(ch.get(delta, 0))})"
+            )
+
+    if state["kb_results"]:
+        parts.append("\n## 知识库参考")
+        for r in state["kb_results"][:6]:
+            title = r.get("metadata", {}).get("title", "")
+            content = r.get("content", "")[:200]
+            parts.append(f"---\n{title}\n{content}")
+
+    return "\n".join(parts)
+
+
+async def generate_plan(state: PlanState) -> dict:
+    """Step 2: 调用 LLM 生成结构化方案"""
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+    prompt = await build_prompt(state)
+    messages = [SystemMessage(content=prompt)]
+    try:
+        response = await llm.ainvoke(messages)
+        answer = response.content
+        # 解析 JSON
+        import json
+        try:
+            # 提取 JSON 块
+            start = answer.find("{")
+            end = answer.rfind("}") + 1
+            if start >= 0 and end > start:
+                json_str = answer[start:end]
+                parsed = json.loads(json_str)
+                return {"full_response": parsed, "overview": parsed.get("overview", "")}
+        except (json.JSONDecodeError, Exception) as e:
+            logger.warning("解析方案 JSON 失败,使用原始文本: %s", e)
+        return {"full_response": {"raw": answer}, "overview": answer[:200]}
+    except Exception as e:
+        logger.error("LLM 生成方案失败: %s", e)
+        return {"error": str(e)}
+
+
+async def regenerate_section(state: PlanState) -> dict:
+    """重新生成指定 section"""
+    section_key = state.get("section", "nutrition")
+    feedback = state.get("feedback", "")
+    existing_content = state.get("existing_section_content", "")
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.3,
+    )
+
+    # 构建上下文摘要
+    ctx_parts = []
+    for m in state.get("members_info", []):
+        ctx_parts.append(f"- {m['name']} (年龄: {m['age']})")
+    if state.get("goal"):
+        ctx_parts.append(f"目标: {state['goal']}")
+    if state.get("abnormal_indicators"):
+        for ind in state["abnormal_indicators"][:5]:
+            ctx_parts.append(f"- {ind['member']}: {ind['indicator']}={ind['value']}")
+
+    regenerate_template = await get_prompt("health_plan_regenerate") or REGENERATE_SECTION_PROMPT
+    try:
+        prompt = regenerate_template.format(
+            existing_section_content=existing_content[:500],
+            feedback=feedback,
+            context_summary="\n".join(ctx_parts),
+        )
+    except (KeyError, IndexError, ValueError):
+        logger.warning("Java 配置的 health_plan_regenerate 模板缺少占位符,回退本地模板")
+        prompt = REGENERATE_SECTION_PROMPT.format(
+            existing_section_content=existing_content[:500],
+            feedback=feedback,
+            context_summary="\n".join(ctx_parts),
+        )
+    try:
+        response = await llm.ainvoke([SystemMessage(content=prompt)])
+        return {"regenerated_content": response.content}
+    except Exception as e:
+        logger.error("重新生成方案 section 失败: %s", e)
+        return {"error": str(e)}
+
+
+def create_health_plan_graph():
+    builder = StateGraph(PlanState)
+    builder.add_node("collect_data", collect_data)
+    builder.add_node("generate_plan", generate_plan)
+    builder.add_node("regenerate_section", regenerate_section)
+    builder.add_edge(START, "collect_data")
+    builder.add_edge("collect_data", "generate_plan")
+    builder.add_edge("generate_plan", END)
+    # regenerate_section 从外部直接调用,不走图
+    graph = builder.compile()
+    return graph

+ 67 - 0
cfc-langgraph/app/graphs/innate_portrait_graph.py

@@ -0,0 +1,67 @@
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.config import settings
+from app.monitoring import monitor_agent
+from app.prompt_service import get_prompt
+import logging
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一位融合中国传统文化与现代心理学的家庭成长解读师。
+
+请根据用户的先天画像数据,生成一段温情、专业、可执行的成长解读文案。
+要求:
+1. 用第二人称"你"称呼
+2. 先认可先天特质优势,再给出1-2条心维度成长建议
+3. 语气温暖克制,避免玄学恐吓或过度承诺
+4. 800字以内,用中文,分2-3段
+5. 以"心能量小贴士"收尾,给一个当天就能做的行动
+"""
+
+
+class InnatePortraitAgent:
+    def __init__(self):
+        self.llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=settings.llm_temperature,
+        )
+
+    @monitor_agent("innate_portrait")
+    async def run(self, portrait: dict) -> dict:
+        """生成先天画像解读,失败返回空 reading(调用方降级模板)"""
+        try:
+            source_summary = self._summarize(portrait)
+            messages = [
+                SystemMessage(content=await get_prompt("innate_portrait") or SYSTEM_PROMPT),
+                HumanMessage(content=f"先天画像数据:\n{source_summary}"),
+            ]
+            response = await self.llm.ainvoke(messages)
+            return {"reading": response.content.strip()}
+        except Exception as e:
+            logger.warning("先天画像解读生成失败: %s", e)
+            return {"reading": ""}
+
+    @staticmethod
+    def _summarize(portrait: dict) -> str:
+        parts = []
+        if portrait.get("zodiac"):
+            parts.append(f"生肖: {portrait['zodiac']}")
+        if portrait.get("bloodType"):
+            parts.append(f"血型: {portrait['bloodType']}")
+        if portrait.get("wuxingElements"):
+            parts.append(f"五行: {portrait['wuxingElements']}")
+        if portrait.get("mindBaseScore") is not None:
+            parts.append(f"心先天基础分: {portrait['mindBaseScore']}")
+        if portrait.get("wisdomBaseScore") is not None:
+            parts.append(f"智先天基础分: {portrait['wisdomBaseScore']}")
+        if portrait.get("eightCharacters"):
+            parts.append(f"八字四柱: {portrait['eightCharacters']}")
+        ns = portrait.get("numSoul") or {}
+        if ns.get("lifePath") is not None:
+            parts.append(
+                f"生命灵数: {ns['lifePath']}"
+                + (f"({ns['lifePathTitle']})" if ns.get("lifePathTitle") else "")
+            )
+        return "\n".join(parts) if parts else "暂无画像数据"

+ 159 - 0
cfc-langgraph/app/graphs/nutrition_graph.py

@@ -0,0 +1,159 @@
+"""AI 营养助手 LangGraph — 基于健康报告的个性化营养建议"""
+from typing import TypedDict
+from langgraph.graph import StateGraph, START, END
+from langgraph.checkpoint.memory import MemorySaver
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.tools.java_client import JavaClient
+from app.tools.product_tools import (
+    search_product_by_keyword,
+    search_article_by_keyword,
+)
+from app.memory.store import MemoryManager
+from app.config import settings
+from app.prompt_service import get_prompt
+from app.portrait_service import get_user_portrait_text
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class NutritionState(TypedDict):
+    query: str
+    user_id: int
+    conversation_id: str
+    child_id: int | None
+    report_id: int | None
+    context: dict | None
+    answer: str | None
+    tasks: list[dict]
+    sources: list[dict]
+    messages: list | None
+
+
+DEFAULT_NUTRITION_PROMPT = """你是一个儿童营养健康顾问,专注于基于检测报告提供精准的营养改善建议。
+
+你的能力:
+1. 解读儿童健康报告(菌群、营养指标、体检数据)
+2. 基于报告数据推荐合适的营养产品和膳食方案
+3. 结合孩子体质给出个性化的饮食建议
+4. 推荐相关的健康活动和科普文章
+
+回答原则:
+1. 用中文,语气温暖专业,像营养师一样亲切
+2. 必须基于报告数据给出建议,不凭空猜测
+3. 引用知识库中的营养素/食物信息作为证据
+4. 需要产品推荐时使用搜索工具,说明推荐理由
+5. 生成 [TASK: {"title": "任务名", "dimension": "身", "points": 10, "frequency": "每天"}] 标记创建营养行动任务
+6. 严重健康问题建议咨询专业医生或营养师
+7. 不要编造医学建议,不夸大效果
+"""
+
+
+def create_nutrition_graph():
+    """创建营养助手 StateGraph"""
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=settings.llm_temperature,
+    )
+
+    from app.rag.embeddings import get_embeddings
+    embeddings = get_embeddings()
+    memory_mgr = MemoryManager(embeddings)
+    java = JavaClient()
+
+    llm_with_tools = llm.bind_tools([
+        search_product_by_keyword,
+        search_article_by_keyword,
+    ])
+
+    builder = StateGraph(NutritionState)
+
+    async def generate_answer(state: NutritionState) -> dict:
+        """核心 LLM 调用 + 画像注入"""
+        # 加载营养助手 prompt
+        nutrition_prompt = await get_prompt("nutrition_assistant") or DEFAULT_NUTRITION_PROMPT
+        messages = [SystemMessage(content=nutrition_prompt)]
+
+        # 画像注入(在人格 prompt 之后)
+        member_id = state.get("child_id")
+        portrait_text = await get_user_portrait_text(java, state["user_id"], member_id)
+        if portrait_text:
+            messages.insert(1, SystemMessage(content=portrait_text))
+
+        # 家庭上下文
+        ctx = state.get("context") or {}
+        if ctx:
+            ctx_parts = []
+            if ctx.get("child_id"):
+                ctx_parts.append(f"孩子ID: {ctx['child_id']}")
+            if ctx.get("family_id"):
+                ctx_parts.append(f"家庭ID: {ctx['family_id']}")
+            if ctx.get("report_id"):
+                ctx_parts.append(f"报告ID: {ctx['report_id']}")
+            if ctx_parts:
+                messages.append(SystemMessage(content="用户背景信息: " + ", ".join(ctx_parts)))
+
+        # 长期记忆
+        try:
+            memories = await memory_mgr.recall(state["user_id"], state["query"])
+            if memories:
+                mem_text = "\n".join([f"- {m}" for m in memories[:3]])
+                messages.append(SystemMessage(content=f"该用户的历史咨询记录:\n{mem_text}"))
+        except Exception as e:
+            logger.warning("召回营养记忆失败: %s", e)
+
+        # 用户消息
+        messages.append(HumanMessage(content=state["query"]))
+
+        response = await llm_with_tools.ainvoke(messages)
+        answer = response.content
+
+        # 提取任务和来源
+        tasks = []
+        sources = []
+        if response.response_metadata.get("tool_calls"):
+            for tc in response.response_metadata["tool_calls"]:
+                sources.append({
+                    "type": "tool",
+                    "name": tc.get("name", ""),
+                    "input": tc.get("args", {}),
+                })
+
+        return {
+            "answer": answer,
+            "tasks": tasks,
+            "sources": sources,
+            "messages": [
+                {"role": "user", "content": state["query"]},
+                {"role": "assistant", "content": answer},
+            ],
+        }
+
+    async def save_memory(state: NutritionState) -> dict:
+        """保存对话到长期记忆"""
+        try:
+            if state.get("messages"):
+                await memory_mgr.save_conversation(
+                    state["user_id"],
+                    state.get("conversation_id") or f"nutrition_{state['user_id']}",
+                    state["messages"],
+                )
+        except Exception as e:
+            logger.warning("保存营养记忆失败: %s", e)
+        return {}
+
+    # 构建图
+    builder.add_node("generate_answer", generate_answer)
+    builder.add_node("save_memory", save_memory)
+
+    builder.add_edge(START, "generate_answer")
+    builder.add_edge("generate_answer", "save_memory")
+    builder.add_edge("save_memory", END)
+
+    checkpointer = MemorySaver()
+    graph = builder.compile(checkpointer=checkpointer)
+
+    return graph

+ 141 - 0
cfc-langgraph/app/graphs/portrait_generation_graph.py

@@ -0,0 +1,141 @@
+"""用户画像生成/重画 LangGraph
+
+输入(由 Java 传入):
+- user_id: 用户ID
+- member_id: 成员ID(可空)
+- previous_portrait: 旧画像文本(重画时传入,首次生成为 None)
+- profile_snapshot: 五维画像快照 dict(含 member/dimension_scores/body_metrics/mind_metrics/problem_domains)
+- behavior_summary: 行为摘要 dict
+
+输出:
+- portrait_text: 生成的画像文本(中文,自然语言描述)
+"""
+from typing import TypedDict
+from langgraph.graph import StateGraph, START, END
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.config import settings
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class PortraitGenerationState(TypedDict):
+    user_id: int
+    member_id: int | None
+    previous_portrait: str | None
+    profile_snapshot: dict | None
+    behavior_summary: dict | None
+    portrait_text: str | None
+
+
+SYSTEM_PROMPT = """你是「浠艾福」家庭成长平台的 AI 画像分析师。
+
+任务:根据用户的行为数据、五维能量指标、健康画像,生成一段自然语言的「用户画像」文本。
+
+画像用途:作为后续所有 AI 对话(健康教练、管家、营养师、通用聊天)的 SystemMessage 注入,帮助 AI 更懂用户,给出更个性化的建议。
+
+生成要求:
+1. 语言自然、温暖、具体,像一位了解家庭的成长顾问写的观察笔记
+2. 必须包含:核心特质、行为模式、关注点、潜在需求
+3. 长度:200-500 字,不要过长
+4. 不要列举原始数据(如"身 7.2 智 6.5"),要转化为洞察(如"身体维度相对突出,但智力维度有提升空间")
+5. 如有 previous_portrait,重画时要体现"变化"与"延续":哪些特质稳定,哪些有新变化,原因可能是什么
+
+输出格式:纯文本,无 JSON,无标记。"""
+
+
+def create_portrait_generation_graph():
+    llm = ChatOpenAI(
+        model=settings.llm_model,
+        api_key=settings.llm_api_key,
+        base_url=settings.llm_base_url,
+        temperature=0.7,
+    )
+
+    builder = StateGraph(PortraitGenerationState)
+
+    async def generate_portrait(state: PortraitGenerationState) -> dict:
+        previous = state.get("previous_portrait")
+        profile = state.get("profile_snapshot") or {}
+        behavior = state.get("behavior_summary") or {}
+
+        context_parts = []
+
+        if profile:
+            member = profile.get("member") or {}
+            name = member.get("name", "用户")
+            age = member.get("age")
+            gender = member.get("gender")
+            context_parts.append(f"用户:{name},{age}岁,{gender}")
+
+            dims = profile.get("dimension_scores") or {}
+            if dims:
+                context_parts.append(
+                    f"五维评分:身 {dims.get('body','?')} 智 {dims.get('wisdom','?')} "
+                    f"心 {dims.get('mind','?')} 行 {dims.get('action','?')} 富 {dims.get('wealth','?')}"
+                )
+
+            body = profile.get("body_metrics") or {}
+            if body.get("sleep_dur_avg"):
+                context_parts.append(f"平均睡眠:{body['sleep_dur_avg']}h/天")
+            if body.get("exercise_count_week"):
+                context_parts.append(f"周运动:{body['exercise_count_week']}次")
+
+            mind = profile.get("mind_metrics") or {}
+            if mind.get("stress_avg"):
+                context_parts.append(f"平均压力:{mind['stress_avg']}/10")
+
+            problems = profile.get("problem_domains") or []
+            if problems:
+                context_parts.append(f"关注问题:{', '.join(problems[:5])}")
+
+        if behavior:
+            context_parts.append("行为摘要:" + str(behavior))
+
+        context_text = "\n".join(context_parts) or "暂无额外数据"
+
+        if previous:
+            human_content = f"""【重画任务】请基于以下最新数据,重新生成用户画像。
+
+【原画像(参考)】:
+{previous}
+
+【最新数据】:
+{context_text}
+
+要求:保留原画像中仍有效的核心特质,更新已变化的部分,体现"变化与延续"。"""
+        else:
+            human_content = f"""【生成任务】请基于以下数据,生成用户画像。
+
+【数据】:
+{context_text}"""
+
+        messages = [
+            SystemMessage(content=SYSTEM_PROMPT),
+            HumanMessage(content=human_content),
+        ]
+
+        response = await llm.ainvoke(messages)
+        portrait_text = response.content.strip()
+
+        logger.info("生成画像完成: user_id=%d, member_id=%s, len=%d",
+                    state["user_id"], state.get("member_id"), len(portrait_text))
+
+        return {"portrait_text": portrait_text}
+
+    builder.add_node("generate_portrait", generate_portrait)
+    builder.add_edge(START, "generate_portrait")
+    builder.add_edge("generate_portrait", END)
+
+    return builder.compile()
+
+
+_portrait_graph = None
+
+
+def get_portrait_graph():
+    global _portrait_graph
+    if _portrait_graph is None:
+        _portrait_graph = create_portrait_generation_graph()
+    return _portrait_graph

+ 442 - 0
cfc-langgraph/app/graphs/question_generation_graph.py

@@ -0,0 +1,442 @@
+"""生成五维自检题目图
+
+基于用户画像(分数、历史数据、行为数据)生成 20 道情境化问卷题目。
+与现有的 self_check_analysis_graph(解读建议)和 self_check_trend_graph(趋势分析)并存。
+
+对外接口:
+  POST /api/v1/question-generate (在 app/api/question_generate.py 中定义)
+"""
+
+import json
+import logging
+from typing import TypedDict, Optional, List, Dict, Any
+from langgraph.graph import StateGraph, START, END
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.llm.client import get_llm
+from app.monitoring import monitor_agent
+from app.prompt_service import get_prompt
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一个专业的五维主动健康评估问卷设计师。请根据用户画像生成 20 道高质量的自检题目。
+
+**五维理论约束(必须严格遵守)**:
+
+
+### 维度定义
+- **身(body)**: 物理健康——睡眠、运动、身体状态(五行:土)
+- **智(wisdom)**: 学习认知——成长型思维、知识输入(五行:金)
+- **富(wealth)**: 利他创富——财务素养、资源分享(五行:水)
+- **行(action)**: 人际和谐——关系、领导、社交(五行:木)
+- **心(mind)**: 精神情绪——情绪稳定、自我接纳(五行:火)
+
+### 计分规则
+- A=3分, B=2分, C=1分, D=0分, E=跳过不计分
+
+
+### 题目设计要求
+
+1. **情境化叙事**:每道题必须有一个具体的生活/工作场景,而非直接询问事实。
+   ❌ 错误:"你每周运动几次?"
+   ✅ 正确:"周末清晨,你本可以去跑步,但今天选择了..."
+
+2. **中性语言**:避免引导性问题,不暗示正确答案。
+
+3. **四选一格式**:选项必须包含 A/B/C/D/E,E 代表"跳过/不适用"。
+
+4. **维度映射**:每道题必须明确映射到一个维度代码:body/wisdom/wealth/action/mind(小写)。
+
+5. **避免重复**:绝对不能与已知的 15 题固定题库重复,也不能与用户过往自检记录重复。
+
+6. **子维度关联**:部分题目可关联子维度(如 actionParentChild, driveAutonomy),用于后续细分分析。
+
+
+### 输出格式(严格 JSON)
+
+{
+  "questions": [
+    {
+      "id": 1,
+      "dimension": "body",
+      "text": "情境描述...",
+      "options": {
+        "A": "选项A文本",
+        "B": "选项B文本",
+        "C": "选项C文本",
+        "D": "选项D文本",
+        "E": "跳过"
+      },
+      "sub_dim": null
+    }
+    // ... 共20道
+  ],
+  "rationale": "生成 rationale,解释每道题的维度选择逻辑",
+  "dimension_distribution": {
+    "body": 4,
+    "wisdom": 4,
+    "wealth": 4,
+    "action": 4,
+    "mind": 4
+  }
+}
+
+}"""
+
+
+class GraphState(TypedDict):
+    """问题生成状态"""
+
+    # 输入
+    user_id: int
+    user_profile: Dict[str, Any]  # 来自 analyze_user_profile
+    dimensions_hint: Optional[List[str]]  # 如 ["body", "wisdom"]
+    count: int  # 题目数量,默认20
+    exclude_ids: List[int]  # 避免重复的历史题目ID
+
+    # 中间状态
+    selected_dimensions: List[str]  # 选择的维度列表
+    dim_allocation: Dict[str, int]  # 各维度题目分配
+    generated_questions: List[Dict]  # LLM 生成的原始题目
+
+    # 输出
+    output_questions: List[Dict]  # 经验证、去重后的题目
+    rationale: str  # 生成 rationale
+    dimension_distribution: Dict[str, int]  # 各维度题目数
+
+    # 元数据
+    start_time: float
+    generation_time: float
+    validation_errors: List[str]
+    retry_count: int
+
+
+async def analyze_user_profile(state: GraphState) -> GraphState:
+    """分析用户画像,确定出题重点
+    
+    从 five_dimension_scores、five_dimension_self_checks、tasks 等表读取数据。
+    对于当前用户(已知 body=58,其他维度未测),确定出题策略。
+    """
+    from sqlalchemy import text
+    from app.tools.sql_client import get_sql_client
+    
+    user_id = state["user_id"]
+    profile = state["user_profile"]
+    
+    # 查询五维分数
+    sql = text("SELECT dimension_code, score FROM five_dimension_scores WHERE user_id = :uid ORDER BY sort_order")
+    scores_result = await get_sql_client().fetch_all(sql, {"uid": user_id})
+    dim_scores = {row["dimension_code"]: row["score"] for row in scores_result} if scores_result else {}
+    
+    # 查询历史自检记录
+    sql = text("SELECT question_ids_json FROM five_dimension_self_checks WHERE user_id = :uid ORDER BY created_at DESC LIMIT 1")
+    last_check = await get_sql_client().fetch_one(sql, {"uid": user_id})
+    previous_question_ids = []
+    if last_check and last_check.question_ids_json:
+        try:
+            previous_question_ids = json.loads(last_check.question_ids_json)
+        except:
+            pass
+    
+    # 构建画像
+    profile.update({
+        "dim_scores": dim_scores,
+        "previous_question_ids": previous_question_ids,
+        "has_previous_check": last_check is not None,
+    })
+    
+    # 确定维度分配策略
+    all_dims = ["body", "wisdom", "wealth", "action", "mind"]
+    zero_dims = [d for d in all_dims if dim_scores.get(d, 0) == 0]
+    low_dims = [d for d in all_dims if dim_scores.get(d, 0) > 0 and dim_scores.get(d, 0) <= 3]
+    high_dims = [d for d in all_dims if dim_scores.get(d, 0) >= 7]
+    
+    if len(zero_dims) == 5:
+        # 情况 A:全新用户,均衡覆盖
+        dim_allocation = {d: 4 for d in all_dims}
+        rationale = "用户首次自检,均衡覆盖五维"
+    elif len(zero_dims) > 0:
+        # 情况 B:部分维度未测(如 body=58, others=0)
+        dim_allocation = {}
+        for dim in all_dims:
+            dim_allocation[dim] = 5 if dim in zero_dims else 3
+        rationale = f"重点关注未测维度: {zero_dims}"
+    else:
+        # 情况 C:有历史数据
+        # 低分维度 60%,中高分 40%
+        if len(low_dims) > 0:
+            low_ratio = 0.6
+        else:
+            low_ratio = 0.4
+        
+        total = state.get("count", 20)
+        dim_allocation = {}
+        for dim in all_dims:
+            if dim in low_dims:
+                dim_allocation[dim] = max(1, int(total * low_ratio / len(low_dims)))
+            else:
+                dim_allocation[dim] = max(1, int(total * (1 - low_ratio) / len(high_dims) if high_dims else 1))
+        rationale = f"基于历史数据,侧重低分维度: {low_dims}"
+    
+    state["selected_dimensions"] = all_dims  # 始终包含所有维度,满足系统最低门槛
+    state["dim_allocation"] = dim_allocation
+    state["rationale"] = rationale
+    
+    logger.info(f"用户画像分析完成: dim_scores={dim_scores}, dim_allocation={dim_allocation}")
+    return state
+
+
+async def select_dimensions(state: GraphState) -> GraphState:
+    """基于用户画像确定各维度题目数量分配
+    
+    已在 analyze_user_profile 中完成,此节点保持兼容性
+    """
+    # 确保 dim_allocation 已设置
+    if "dim_allocation" not in state:
+        state["dim_allocation"] = {d: 4 for d in ["body", "wisdom", "wealth", "action", "mind"]}
+    return state
+
+
+async def generate_questions(state: GraphState) -> GraphState:
+    """使用 LLM 生成题目
+    
+    基于 dim_allocation 生成对应数量的题目,每个维度包含 A/B/C/D/E 选项
+    """
+    dim_allocation = state["dim_allocation"]
+    count = state.get("count", 20)
+    exclude_ids = state.get("exclude_ids", [])
+    
+    generated = []
+    dim_counts = {d: 0 for d in ["body", "wisdom", "wealth", "action", "mind"]}
+    
+    # 为每个维度生成对应数量的题目
+    for dim, num in dim_allocation.items():
+        for i in range(num):
+            q_id = len(generated) + 1  # 临时 ID,后续会重新排序
+            
+            # 构建 LLM 提示词
+            prompt = f"""生成一道五维自检题目。
+
+**维度**: {dim}
+**情境**: 针对当前用户画像(该维度分数{...})的相关场景
+
+**要求**:
+- 写一道情境化的五维自检题目
+- 4个选项 A/B/C/D,E为"跳过"
+- 选项要中性,不引导用户
+- 严格返回 JSON 格式,不要添加其他文字
+
+**输出格式(单题)**:
+{{
+  "id": {q_id},
+  "dimension": "{dim}",
+  "text": "题目文本",
+  "options": {{
+    "A": "选项A",
+    "B": "选项B", 
+    "C": "选项C",
+    "D": "选项D",
+    "E": "跳过"
+  }},
+  "sub_dim": null
+}}
+"""
+            
+            # 调用 LLM
+            try:
+                llm = get_llm()
+                messages = [
+                    SystemMessage(content=SYSTEM_PROMPT),
+                    HumanMessage(content=prompt),
+                ]
+                response = await llm.ainvoke(messages)
+                text = response.content.strip()
+                
+                # 解析 JSON
+                if "```json" in text:
+                    text = text.split("```json")[1].split("```")[0].strip()
+                elif "```" in text:
+                    text = text.split("```")[1].split("```")[0].strip()
+                
+                q_data = json.loads(text)
+                generated.append(q_data)
+                dim_counts[dim] += 1
+                
+            except Exception as e:
+                logger.warning(f"题目 {q_id} 生成失败: {e}")
+                # 降级:使用模板生成保底题目
+                generated.append({
+                    "id": q_id,
+                    "dimension": dim,
+                    "text": f"关于{dim}维度的情境描述...",
+                    "options": {
+                        "A": "积极正面选项",
+                        "B": "中性选项",
+                        "C": "消极选项",
+                        "D": "完全不适用",
+                        "E": "跳过"
+                    },
+                    "sub_dim": None
+                })
+    
+    state["generated_questions"] = generated
+    state["dimension_distribution"] = dim_counts
+    return state
+
+
+async def validate_questions(state: GraphState) -> GraphState:
+    """验证生成的题目格式和内容"""
+    errors = []
+    generated = state.get("generated_questions", [])
+    dim_counts = {d: 0 for d in ["body", "wisdom", "wealth", "action", "mind"]}
+    
+    for q in generated:
+        # 验证维度
+        if q.get("dimension") not in ["body", "wisdom", "wealth", "action", "mind"]:
+            errors.append(f"题目 {q.get('id', '?')} 维度代码无效: {q.get('dimension')}")
+            continue
+        
+        dim_counts[q["dimension"]] = dim_counts.get(q["dimension"], 0) + 1
+        
+        # 验证选项
+        opts = q.get("options", {})
+        if not all(k in opts for k in ["A", "B", "C", "D", "E"]):
+            errors.append(f"题目 {q.get('id', '?')} 选项格式不完整")
+        
+        # 验证文本
+        if not q.get("text", "").strip():
+            errors.append(f"题目 {q.get('id', '?')} 文本为空")
+    
+    # 检查每维至少 1 题
+    for dim in ["body", "wisdom", "wealth", "action", "mind"]:
+        if dim_counts.get(dim, 0) < 1:
+            errors.append(f"维度 [{dim}] 至少需要 1 题,当前 {dim_counts.get(dim, 0)} 题")
+    
+    # 检查总数
+    if len(generated) < state.get("count", 20):
+        errors.append(f"生成题目数量不足: {len(generated)}/{state.get('count', 20)}")
+    
+    state["validation_errors"] = errors
+    
+    if errors and state.get("retry_count", 0) < 3:
+        # 标记重试
+        state["retry_count"] = state.get("retry_count", 0) + 1
+        # 清除生成的题目,触发重新生成
+        state["generated_questions"] = []
+        state["dimension_distribution"] = {}
+    
+    return state
+
+
+async def avoid_duplicates(state: GraphState) -> GraphState:
+    """去重:确保不与历史题目重复"""
+    generated = state.get("generated_questions", [])
+    exclude_ids = set(state.get("exclude_ids", []))
+    
+    valid_questions = []
+    for q in generated:
+        if q.get("id") not in exclude_ids:
+            valid_questions.append(q)
+        else:
+            logger.info(f"题目 {q.get('id')} 在排除列表中,跳过")
+    
+    # 如果去重后不足,生成补充题目
+    needed = state.get("count", 20) - len(valid_questions)
+    if needed > 0:
+        # 简单的补充:复用已有维度的题目但重新排序
+        for i in range(needed):
+            if generated:
+                q = generated[i % len(generated)]
+                q["id"] = 1000 + i  # 新 ID
+                valid_questions.append(q)
+    
+    state["output_questions"] = valid_questions[:state.get("count", 20)]
+    return state
+
+
+def build_graph():
+    """构建 LangGraph 工作流"""
+    workflow = StateGraph(GraphState)
+    
+    # 添加节点
+    workflow.add_node("analyze_user_profile", analyze_user_profile)
+    workflow.add_node("select_dimensions", select_dimensions)
+    workflow.add_node("generate_questions", generate_questions)
+    workflow.add_node("validate_questions", validate_questions)
+    workflow.add_node("avoid_duplicates", avoid_duplicates)
+    
+    # 设置入口
+    workflow.set_entry_point("analyze_user_profile")
+    
+    # 连接边
+    workflow.add_edge("analyze_user_profile", "select_dimensions")
+    workflow.add_edge("select_dimensions", "generate_questions")
+    workflow.add_edge("generate_questions", "validate_questions")
+    
+    # 条件边:验证通过则去重,失败则重试
+    workflow.add_conditional_edges(
+        "validate_questions",
+        lambda state: "retry" if state.get("validation_errors") else "deduplicate",
+        {
+            "retry": "generate_questions",
+            "deduplicate": "avoid_duplicates",
+        }
+    )
+    
+    workflow.add_edge("avoid_duplicates", END)
+    
+    return workflow.compile()
+
+
+_graph = None
+
+
+def get_graph():
+    global _graph
+    if _graph is None:
+        _graph = build_graph()
+    return _graph
+
+
+async def run_question_gen(user_id: int, count: int = 20, 
+                           difficulty: str = "balanced",
+                           dimensions: Optional[List[str]] = None,
+                           exclude_ids: Optional[List[int]] = None) -> Dict[str, Any]:
+    """运行问题生成工作流的便捷函数
+    
+    Args:
+        user_id: 用户 ID
+        count: 生成题目数量,默认20
+        difficulty: 难度提示(balanced/easy/hard/contextual)
+        dimensions: 指定维度,可选
+        exclude_ids: 需要排除的历史题目 ID
+    
+    Returns:
+        包含生成题目、rationale、dimension_distribution 的字典
+    """
+    start_time = __import__("time").time()
+    
+    # 构建初始状态
+    state: GraphState = {
+        "user_id": user_id,
+        "user_profile": {},  # 将在分析节点中填充
+        "dimensions_hint": dimensions,
+        "count": count,
+        "exclude_ids": exclude_ids or [],
+        "start_time": start_time,
+        "retry_count": 0,
+    }
+    
+    # 执行工作流
+    graph = get_graph()
+    result = await graph.ainvoke(state)
+    
+    generation_time = __import__("time").time() - start_time
+    result["generation_time"] = generation_time
+    
+    return {
+        "questions": result.get("output_questions", []),
+        "rationale": result.get("rationale", ""),
+        "dimension_distribution": result.get("dimension_distribution", {}),
+        "generation_time": generation_time,
+        "fallback_used": len(result.get("validation_errors", [])) > 0,
+    }

+ 80 - 0
cfc-langgraph/app/graphs/recommend_graph.py

@@ -0,0 +1,80 @@
+from langchain_openai import ChatOpenAI
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.tools.product_tools import search_product_by_keyword, search_activity_by_keyword, search_article_by_keyword
+from app.config import settings
+from app.monitoring import monitor_agent
+import json
+import logging
+from app.prompt_service import get_prompt
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一个儿童成长营养推荐助手。根据用户的需求和营养标签, 推荐合适的商品、活动或文章。
+
+推荐原则:
+1. 首先尝试使用搜索工具查找匹配的内容
+2. 如果搜索结果为空, 基于你的知识给出建议
+3. 每项推荐必须附带推荐理由
+4. 以 JSON 格式输出推荐结果
+
+输出格式:
+{
+    "items": [
+        {
+            "source": "tool" 或 "knowledge",
+            "type": "product" / "activity" / "article",
+            "id": 数字,
+            "name": "名称",
+            "description": "描述",
+            "reason": "为什么推荐这个"
+        }
+    ]
+}
+"""
+
+
+class RecommendAgent:
+    def __init__(self):
+        self.llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            temperature=settings.llm_temperature,
+        )
+        self.tools = [
+            search_product_by_keyword,
+            search_activity_by_keyword,
+            search_article_by_keyword,
+        ]
+        self.llm_with_tools = self.llm.bind_tools(self.tools)
+
+    @monitor_agent("recommend")
+    async def run(self, query: str, tags: list[str], limit: int = 5) -> dict:
+        """执行推荐 Agent, 返回推荐结果"""
+        # 如果传入了 tags, 构造搜索关键词
+        search_query = query or " ".join(tags)
+
+        messages = [
+            SystemMessage(content=await get_prompt("recommend") or SYSTEM_PROMPT),
+            HumanMessage(content=f"用户需求: {search_query}\n最大返回数量: {limit}\n请搜索并推荐合适的内容。"),
+        ]
+
+        # LangChain Tool calling 自动完成: LLM 决定调哪个 Tool → 工具返回结果 → LLM 组织回答
+        response = await self.llm_with_tools.ainvoke(messages)
+
+        # 尝试解析 JSON 输出
+        content = response.content
+        try:
+            # 提取 JSON 块
+            if "```json" in content:
+                json_str = content.split("```json")[1].split("```")[0].strip()
+            elif "```" in content:
+                json_str = content.split("```")[1].split("```")[0].strip()
+            else:
+                json_str = content.strip()
+            result = json.loads(json_str)
+            return result
+        except (json.JSONDecodeError, IndexError):
+            # 非 JSON 输出, 包装为文本回答
+            logger.warning("Agent 输出非 JSON, raw: %s", content[:200])
+            return {"items": [], "text": content}

+ 117 - 0
cfc-langgraph/app/graphs/self_check_analysis_graph.py

@@ -0,0 +1,117 @@
+import json
+import logging
+from typing import TypedDict, Optional
+from langgraph.graph import StateGraph, START, END
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.llm.client import get_llm
+from app.monitoring import monitor_agent
+from app.prompt_service import get_prompt
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一位家庭健康顾问,基于五维自检结果(身·智·富·行·心,每维0-9分,满分45)给出个性化建议。
+
+要求:
+1. 对每个低分维度(≤6分)给出1-2句解读和2-3个具体可执行的微行动
+2. 如有历史数据,简要对比趋势(改善/下滑)
+3. 语气温暖口语化,每条解读不超过80字
+4. 最后给出1句家庭整体洞察(30字以内)
+
+返回 JSON(严格格式,不要额外文字):
+{
+  "advice": [
+    {
+      "dimension": "mind",
+      "dimensionName": "心",
+      "interpretation": "你的情绪能量偏低,可能最近压力较大,建议...",
+      "microActions": ["今晚睡前做10分钟深呼吸", "和伴侣约定每周一次夜谈"],
+      "fallbackUsed": false
+    }
+  ],
+  "familyInsight": "建议从行动维度入手,关系顺畅了内心才能安定"
+}
+"""
+
+
+class GraphState(TypedDict):
+    scores: dict
+    question_ids: list
+    user_id: int
+    recent_history: list
+    advice: Optional[dict]
+    error: Optional[str]
+
+
+class SelfCheckAnalysisAgent:
+    def __init__(self):
+        self.llm = get_llm()
+
+    @monitor_agent("self_check_analysis")
+    async def run(self, scores: dict, question_ids: list, user_id: int, recent_history: list) -> dict:
+        try:
+            score_summary = "\n".join(
+                f"{v.get('dimensionName', k)}({k}): {v.get('score', 0)}分"
+                for k, v in scores.items()
+            )
+            history_summary = ""
+            if recent_history:
+                history_summary = "历史趋势:\n" + "\n".join(
+                    f"- {h.get('createdAt', '')}: 总分{h.get('totalScore', 0)}分"
+                    for h in recent_history[:3]
+                )
+            messages = [
+                SystemMessage(content=await get_prompt("self_check_analysis") or SYSTEM_PROMPT),
+                HumanMessage(content=f"用户ID: {user_id}\n当前自检得分:\n{score_summary}\n{history_summary}"),
+            ]
+            response = await self.llm.ainvoke(messages)
+            text = response.content.strip()
+            if "```json" in text:
+                text = text.split("```json")[1].split("```")[0].strip()
+            elif "```" in text:
+                text = text.split("```")[1].split("```")[0].strip()
+            data = json.loads(text)
+            advice_list = data.get("advice", [])
+            for item in advice_list:
+                item.setdefault("fallbackUsed", False)
+            if advice_list:
+                advice_list[0]["familyInsight"] = data.get("familyInsight", "")
+            return {"advice": {"advice_json": json.dumps(advice_list, ensure_ascii=False), "fallback_used": False}}
+        except Exception as e:
+            logger.warning("自检建议生成失败: %s", e)
+            return {"advice": {"advice_json": None, "fallback_used": True}}
+
+
+def build_graph():
+    agent = SelfCheckAnalysisAgent()
+
+    def parse_input(state: GraphState) -> GraphState:
+        return state
+
+    async def call_llm(state: GraphState) -> dict:
+        return await agent.run(state["scores"], state["question_ids"], state["user_id"], state["recent_history"])
+
+    def validate(state: GraphState) -> GraphState:
+        adv = state.get("advice")
+        if adv is None or adv.get("advice_json") is None:
+            return {**state, "error": "AI 建议生成失败"}
+        return state
+
+    graph = StateGraph(GraphState)
+    graph.add_node("parse", parse_input)
+    graph.add_node("llm", call_llm)
+    graph.add_node("validate", validate)
+    graph.add_edge(START, "parse")
+    graph.add_edge("parse", "llm")
+    graph.add_edge("llm", "validate")
+    graph.add_edge("validate", END)
+    return graph.compile()
+
+
+_graph = None
+
+
+def get_graph():
+    global _graph
+    if _graph is None:
+        _graph = build_graph()
+    return _graph

+ 77 - 0
cfc-langgraph/app/graphs/self_check_trend_graph.py

@@ -0,0 +1,77 @@
+import json
+import logging
+from typing import TypedDict, Optional
+from langgraph.graph import StateGraph, START, END
+from langchain_core.messages import SystemMessage, HumanMessage
+from app.llm.client import get_llm
+from app.monitoring import monitor_agent
+from app.prompt_service import get_prompt
+
+logger = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """分析用户近3次五维自检趋势,输出:
+- aiInsight: 趋势解读(2-3句,指出最大变化维度和可能原因,口语化)
+- trendSummary: 各维度 delta 简写(如"身-2 智+1 富0 行-1 心+2")
+返回 JSON:{"aiInsight": "...", "trendSummary": "..."}
+"""
+
+
+class TrendState(TypedDict):
+    history: list
+    user_id: int
+    insight: Optional[dict]
+    error: Optional[str]
+
+
+class SelfCheckTrendAgent:
+    def __init__(self):
+        self.llm = get_llm()
+
+    @monitor_agent("self_check_trend")
+    async def run(self, history: list, user_id: int) -> dict:
+        try:
+            if len(history) < 2:
+                return {"insight": {"aiInsight": "自检次数不足,建议完成至少2次自检后查看趋势", "trendSummary": ""}, "error": None}
+            history_text = "\n".join(
+                f"{h.get('createdAt', '')}: 总分{h.get('totalScore', 0)}," +
+                " ".join(f"{d.get('name','')}{d.get('score',0)}分" for d in h.get('dimensions', []))
+                for h in history[-3:]
+            )
+            messages = [
+                SystemMessage(content=await get_prompt("self_check_trend") or SYSTEM_PROMPT),
+                HumanMessage(content=f"用户{user_id}的自检历史:\n{history_text}"),
+            ]
+            response = await self.llm.ainvoke(messages)
+            text = response.content.strip()
+            if "```json" in text:
+                text = text.split("```json")[1].split("```")[0].strip()
+            elif "```" in text:
+                text = text.split("```")[1].split("```")[0].strip()
+            data = json.loads(text)
+            return {"insight": data, "error": None}
+        except Exception as e:
+            logger.warning("趋势分析失败: %s", e)
+            return {"insight": {"aiInsight": "", "trendSummary": ""}, "error": str(e)}
+
+
+def build_trend_graph():
+    agent = SelfCheckTrendAgent()
+
+    async def call_llm(state: TrendState) -> dict:
+        return await agent.run(state["history"], state["user_id"])
+
+    graph = StateGraph(TrendState)
+    graph.add_node("llm", call_llm)
+    graph.add_edge(START, "llm")
+    graph.add_edge("llm", END)
+    return graph.compile()
+
+
+_trend_graph = None
+
+
+def get_trend_graph():
+    global _trend_graph
+    if _trend_graph is None:
+        _trend_graph = build_trend_graph()
+    return _trend_graph

+ 0 - 0
cfc-langgraph/app/llm/__init__.py


+ 3 - 0
cfc-langgraph/app/llm/client.py

@@ -0,0 +1,3 @@
+from src.llm.client import get_llm
+
+__all__ = ["get_llm"]

+ 54 - 0
cfc-langgraph/app/log_config.py

@@ -0,0 +1,54 @@
+import logging
+import logging.handlers
+import json
+import sys
+import os
+from datetime import datetime, timezone
+
+
+class JsonFormatter(logging.Formatter):
+    """JSON 日志格式化器 (适合生产环境日志聚合)"""
+
+    def format(self, record: logging.LogRecord) -> str:
+        log_entry = {
+            "timestamp": datetime.now(timezone.utc).isoformat(),
+            "level": record.levelname,
+            "logger": record.name,
+            "message": record.getMessage(),
+        }
+        if hasattr(record, "trace_id"):
+            log_entry["trace_id"] = record.trace_id
+        if record.exc_info and record.exc_info[0]:
+            log_entry["exception"] = self.formatException(record.exc_info)
+        return json.dumps(log_entry, ensure_ascii=False)
+
+
+def setup_logging(level: str = "INFO", json_format: bool = False):
+    root = logging.getLogger()
+    root.setLevel(getattr(logging, level.upper(), logging.INFO))
+
+    root.handlers.clear()
+
+    # 控制台 handler
+    console_handler = logging.StreamHandler(sys.stdout)
+    if json_format:
+        console_handler.setFormatter(JsonFormatter())
+    else:
+        console_handler.setFormatter(logging.Formatter(
+            "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
+            datefmt="%Y-%m-%d %H:%M:%S",
+        ))
+    root.addHandler(console_handler)
+
+    # 可选:文件落盘 (LOG_FILE 环境变量指定路径,默认不开启)
+    log_file = os.getenv("LOG_FILE")
+    if log_file:
+        file_handler = logging.handlers.RotatingFileHandler(
+            log_file, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8"
+        )
+        file_handler.setFormatter(JsonFormatter())
+        root.addHandler(file_handler)
+
+    logging.getLogger("httpx").setLevel(logging.WARNING)
+    logging.getLogger("chromadb").setLevel(logging.WARNING)
+    logging.getLogger("langchain").setLevel(logging.WARNING)

+ 88 - 0
cfc-langgraph/app/main.py

@@ -0,0 +1,88 @@
+import os
+import time
+import asyncio
+import logging
+from fastapi import FastAPI, Request
+from app.api import health, recommend, chat, analyze, tongue, adapter, report_parse, meal, logs, audio, innate_portrait, self_check, knowledge_base, portrait, article_quiz, indicator_classify
+from app import monitoring
+from src.app import router as questionnaire_router
+from app.middleware import RequestLogMiddleware
+
+logger = logging.getLogger(__name__)
+
+app = FastAPI(title="cfc-langgraph", version="0.3.0")
+
+# 注册请求日志中间件(纯 ASGI,避免 BaseHTTPMiddleware 消费 body 导致单 worker 死锁)
+app.add_middleware(RequestLogMiddleware)
+
+app.include_router(health.router)
+app.include_router(recommend.router)
+app.include_router(chat.router)
+app.include_router(analyze.router)
+app.include_router(tongue.router)
+app.include_router(adapter.router)
+app.include_router(monitoring.router)
+app.include_router(questionnaire_router)
+app.include_router(report_parse.router)
+app.include_router(meal.router)
+app.include_router(audio.router)
+app.include_router(logs.router)
+app.include_router(innate_portrait.router)
+app.include_router(self_check.router)
+app.include_router(self_check.router)
+app.include_router(knowledge_base.router)
+app.include_router(portrait.router)
+app.include_router(article_quiz.router)
+app.include_router(indicator_classify.router)
+
+
+@app.on_event("startup")
+async def startup():
+    from app.config import settings
+    from app.log_config import setup_logging
+
+    json_logs = os.getenv("JSON_LOGS", "false").lower() == "true"
+    setup_logging(level=settings.log_level, json_format=json_logs)
+
+    # 初始化 faster-whisper STT 模型
+    from app.audio.transcriber import init_model
+    init_model()
+
+    if os.getenv("LANGCHAIN_TRACING_V2", "").lower() == "true":
+        logger.info(
+            "LangSmith 已启用: project=%s, api_key=%s...",
+            settings.langchain_project,
+            settings.langchain_api_key[:8] if settings.langchain_api_key else "none",
+        )
+
+    from app.rag.retriever import RagRetriever
+    retriever = RagRetriever()
+    await retriever.initialize()
+
+    # 初始化 LangGraph checkpointer(必须在运行中的事件循环内创建 AsyncSqliteSaver)
+    from app.checkpointer import init_checkpointer
+    await init_checkpointer()
+
+    async def schedule_kb_sync():
+        # 首次同步延迟 120s,让 healthcheck 先通过,避免 worker 刚启动就被阻塞
+        await asyncio.sleep(120)
+        while True:
+            try:
+                from app.tasks.knowledge_sync import sync_knowledge_base
+                await sync_knowledge_base()
+            except Exception as e:
+                logger.warning("知识库同步失败: %s", e)
+            await asyncio.sleep(3600)
+
+    if os.getenv("KB_SYNC_ENABLED", "true").lower() == "false":
+        logger.info("知识库定时同步已禁用 (KB_SYNC_ENABLED=false)")
+    else:
+        asyncio.create_task(schedule_kb_sync())
+        logger.info("知识库定时同步已启动 (首次延迟 120s,间隔 3600s)")
+
+
+@app.on_event("shutdown")
+async def shutdown():
+    from app.tools.java_client import JavaClient
+    client = JavaClient()
+    await client.close()

+ 1 - 0
cfc-langgraph/app/memory/__init__.py

@@ -0,0 +1 @@
+from .store import MemoryManager

+ 59 - 0
cfc-langgraph/app/memory/store.py

@@ -0,0 +1,59 @@
+import os
+import logging
+from datetime import datetime
+
+logger = logging.getLogger(__name__)
+
+
+class MemoryManager:
+    """轻量级记忆管理器 - 仅保存对话历史到向量数据库
+    
+    不再使用 langchain.memory(已废弃),直接实现核心功能:
+    - Layer 3 - 语义记忆:每次对话后向量化存储,供后续会话召回
+    """
+
+    def __init__(self, embeddings):
+        """初始化记忆管理器
+        
+        Args:
+            embeddings: 嵌入模型实例 (OpenAIEmbeddings 或其他兼容接口)
+        """
+        self.embeddings = embeddings
+        # Layer 3 向量库:历史对话记忆
+        from langchain_chroma import Chroma
+        self.memory_vectorstore = Chroma(
+            collection_name="user_memory",
+            embedding_function=self.embeddings,
+            persist_directory=os.path.expanduser("~/.cfc/langgraph/memory"),
+        )
+
+    async def save_conversation(self, user_id: int, conversation_id: str,
+                                messages: list[dict]):
+        """会话结束后保存到向量记忆库"""
+        texts = []
+        for msg in messages:
+            role = msg.get("role", "unknown")
+            content = msg.get("content", "")
+            texts.append(f"[{role}] {content}")
+
+        full_text = "\n".join(texts)
+        metadata = {
+            "user_id": user_id,
+            "conversation_id": conversation_id,
+            "timestamp": str(datetime.now()),
+        }
+
+        await self.memory_vectorstore.aadd_texts(
+            texts=[full_text],
+            metadatas=[metadata],
+        )
+        logger.info("已保存对话到向量记忆:conv=%s, user=%s", conversation_id, user_id)
+
+    async def recall(self, user_id: int, query: str, k: int = 3) -> list[str]:
+        """语义召回:查询与 query 最相似的历史对话片段"""
+        results = self.memory_vectorstore.similarity_search(
+            query,
+            k=k,
+            filter={"user_id": user_id},
+        )
+        return [doc.page_content for doc in results]

+ 140 - 0
cfc-langgraph/app/middleware.py

@@ -0,0 +1,140 @@
+"""请求日志中间件 — 记录最近 MAX_ENTRIES 条请求到内存
+
+实现为纯 ASGI 中间件(而非 BaseHTTPMiddleware),原因:
+- BaseHTTPMiddleware 中先 `await request.body()` 再 `call_next(request)` 会消费请求体,
+  导致下游 handler 再次 receive 时拿不到 body,POST 请求死锁/挂起;
+- 单 worker 部署下,一个请求挂起会卡死整个 worker,所有请求(含 /api/v1/logs)超时。
+
+纯 ASGI 中间件通过包装 receive/send 通道缓存请求体与响应状态,既记录日志又不破坏下游请求。
+"""
+import time
+import uuid
+from collections import deque
+import logging
+
+logger = logging.getLogger(__name__)
+
+MAX_ENTRIES = 500
+_request_log: deque = deque(maxlen=MAX_ENTRIES)
+
+
+def get_request_log() -> list:
+    """返回请求日志副本(最近在前)"""
+    return list(_request_log)[::-1]
+
+
+def clear_request_log() -> int:
+    """清空日志,返回清空条数"""
+    n = len(_request_log)
+    _request_log.clear()
+    return n
+
+
+def _decode_body(raw: bytes) -> str:
+    """将请求体字节解码为可读文本(截断超长内容)"""
+    if not raw:
+        return ""
+    try:
+        text = raw.decode("utf-8")
+        if len(text) > 2000:
+            text = text[:2000] + "...(truncated)"
+        return text
+    except Exception:
+        return f"<binary {len(raw)} bytes>"
+
+
+class RequestLogMiddleware:
+    """纯 ASGI 请求日志中间件。
+
+    通过包装 receive 通道缓存请求体(不消费、不阻塞下游),
+    通过包装 send 通道捕获响应状态码与响应体,避免破坏原请求。
+    """
+
+    def __init__(self, app):
+        self.app = app
+
+    async def __call__(self, scope, receive, send):
+        if scope["type"] != "http":
+            await self.app(scope, receive, send)
+            return
+
+        start_time = time.perf_counter()
+        method = scope.get("method", "GET")
+        path = scope.get("path", "")
+        client = scope.get("client")
+        client_ip = client[0] if client else "-"
+
+        # 读取或生成 X-Request-ID(Java AiGateway 在每次调用时都会注入 UUID)
+        request_id = None
+        for name, value in scope.get("headers", []):
+            if name == b"x-request-id":
+                request_id = value.decode()
+                break
+        request_id = request_id or str(uuid.uuid4())
+
+        # 带 trace_id 的 adapter:JsonFormatter 会把它写为顶层字段
+        req_logger = logging.LoggerAdapter(logger, {"trace_id": request_id})
+
+        # 缓存请求体(仅对带 body 的方法),不影响下游 receive
+        body_bytes = b""
+        body_cached = False
+
+        async def receive_wrapper():
+            nonlocal body_bytes, body_cached
+            message = await receive()
+            if message["type"] == "http.request":
+                body_bytes += message.get("body", b"")
+                if not message.get("more_body", False):
+                    body_cached = True
+            return message
+
+        # 捕获响应状态码与响应体
+        status_code = None
+        response_chunks = []
+        sent_response_start = False
+
+        async def send_wrapper(message):
+            nonlocal status_code, response_chunks, sent_response_start
+            if message["type"] == "http.response.start":
+                status_code = message.get("status", 500)
+                sent_response_start = True
+            elif message["type"] == "http.response.body":
+                body = message.get("body", b"")
+                if body:
+                    response_chunks.append(body)
+                    total = sum(len(c) for c in response_chunks)
+                    if total > 1000:
+                        response_chunks[:] = [b"".join(response_chunks)[:1000]]
+            return await send(message)
+
+        try:
+            await self.app(scope, receive_wrapper, send_wrapper)
+        except Exception as exc:
+            req_logger.error("REQUEST EXCEPTION: %s %s %.2fs error=%r",
+                          method, path, time.perf_counter() - start_time, exc)
+            if not sent_response_start:
+                from starlette.responses import JSONResponse
+                resp = JSONResponse(status_code=500, content={"detail": str(exc)})
+                await resp(scope, receive, send)
+            status_code = status_code or 500
+
+        elapsed = time.perf_counter() - start_time
+        final_status = status_code if status_code is not None else 500
+
+        entry = {
+            "ts": time.strftime("%H:%M:%S"),
+            "method": method,
+            "path": path,
+            "status": final_status,
+            "duration_ms": round(elapsed * 1000),
+            "client_ip": client_ip,
+            "trace_id": request_id,
+            "body": _decode_body(body_bytes) if body_cached else None,
+            "response": _decode_body(b"".join(response_chunks)[:1000]) if response_chunks else "",
+        }
+        _request_log.appendleft(entry)
+
+        if elapsed > 5:
+            req_logger.warning("SLOW_REQUEST: %s %s %.2fs", method, path, elapsed)
+        else:
+            req_logger.debug("REQUEST: %s %s %.2fs", method, path, elapsed)

+ 3 - 0
cfc-langgraph/app/models/__init__.py

@@ -0,0 +1,3 @@
+from .common import UserContext, SourceInfo
+from .chat import ChatRequest, ChatResponse
+from .recommend import RecommendRequest, RecommendResponse, RecommendItem

+ 13 - 0
cfc-langgraph/app/models/article_quiz.py

@@ -0,0 +1,13 @@
+from pydantic import BaseModel
+from typing import List, Dict, Any
+
+
+class ArticleQuizRequest(BaseModel):
+    article_title: str
+    article_content: str = ""
+    profile_summary: str = ""
+
+
+class ArticleQuizResponse(BaseModel):
+    questions: List[Dict[str, Any]] = []
+    fallback_used: bool = True

+ 18 - 0
cfc-langgraph/app/models/chat.py

@@ -0,0 +1,18 @@
+from pydantic import BaseModel
+from typing import Optional
+from .common import UserContext, SourceInfo
+
+
+class ChatRequest(BaseModel):
+    query: str
+    user_id: int
+    conversation_id: str = ""
+    context: Optional[UserContext] = None
+
+
+class ChatResponse(BaseModel):
+    answer: str
+    conversation_id: str
+    sources: list[SourceInfo] = []
+    tasks: list[dict] = []
+    trace_id: str = ""

+ 19 - 0
cfc-langgraph/app/models/common.py

@@ -0,0 +1,19 @@
+from pydantic import BaseModel
+from typing import Optional
+
+
+class UserContext(BaseModel):
+    """Java 侧传来的业务上下文"""
+    child_id: Optional[int] = None
+    report_id: Optional[int] = None
+    survey_id: Optional[int] = None
+    family_id: Optional[int] = None
+    mascot_code: Optional[str] = None
+    self_check_result: Optional[str] = None  # P1-2: 自检结果 JSON(五维得分+历史)
+
+
+class SourceInfo(BaseModel):
+    """回答引用来源"""
+    type: str  # knowledge / tool
+    title: str
+    score: Optional[float] = None

+ 93 - 0
cfc-langgraph/app/models/health_plan.py

@@ -0,0 +1,93 @@
+from pydantic import BaseModel
+from typing import Literal, Optional, List, Dict, Any
+
+
+class HealthPlanGenerateRequest(BaseModel):
+    member_ids: Optional[str] = None
+    dimensions: Optional[str] = None
+    goal: str = ""
+    family_id: Optional[int] = None
+
+
+class PlanTask(BaseModel):
+    action_type: Literal["buy", "read", "exercise", "checkin", "diet", "activity"]
+    title: str
+    dimension: Literal["body", "mind", "wisdom", "action", "wealth"]
+    frequency: Literal["once", "daily"] = "daily"
+    notes: Optional[str] = None
+
+
+class HealthPlanSection(BaseModel):
+    key: str  # "nutrition" | "diet" | "exercise"
+    title: str
+    content: str  # markdown text
+    items: List[dict] = []  # structured items for UI rendering
+    tasks: List[PlanTask] = []  # machine-readable task intents
+
+
+class HealthPlanResponse(BaseModel):
+    """单成员方案 / 兼容旧结构(扁平 sections)。
+
+    多成员(common+individual)请使用 MultiMemberPlanResponse。
+    本类保留以向后兼容单人方案路径(len(member_ids) <= 1)。
+    """
+    overview: str = ""
+    sections: List[HealthPlanSection] = []
+    abnormal_indicators: List[dict] = []
+    knowledge_sources: List[dict] = []
+    # HL-03/R3:生成时的不确定点(对话式补充提问),无则空列表
+    follow_up_questions: List[dict] = []
+
+
+class PlanPart(BaseModel):
+    """方案的一个逻辑部分:可承载共性(common)或个性(individual)。"""
+    overview: str = ""
+    sections: List[HealthPlanSection] = []
+    abnormal_indicators: List[dict] = []
+    knowledge_sources: List[dict] = []
+    # HL-03/R3:生成时的不确定点(对话式补充提问),无则空列表
+    follow_up_questions: List[dict] = []
+
+
+class MultiMemberPlanResponse(BaseModel):
+    """多人方案:共性 + 各成员个性。
+
+    - common: 适用于全体成员的共性方案部分
+    - individual: 按 member_id 分组的个性方案部分
+    """
+    common: PlanPart = PlanPart()
+    individual: Dict[str, PlanPart] = {}
+    # HL-03/R3:多人方案整体的不确定点(对话式补充提问),无则空列表
+    follow_up_questions: List[dict] = []
+
+    def build_rendered_content(self, member_names: Dict[str, str]) -> str:
+        """把 common+individual 组合渲染为 Markdown 文本(供 planContent 使用)。
+
+        member_names: {memberId: 成员名},用于在标题里标注个性部分归属。
+        """
+        out: List[str] = []
+        out.append("# 健康方案\n\n")
+        common = self.common
+        out.append("## 共性方案\n")
+        if common.overview:
+            out.append("### 方案概述\n\n" + common.overview + "\n\n")
+        for sec in common.sections:
+            out.append(f"## {sec.title}\n\n{sec.content}\n\n")
+        if common.abnormal_indicators:
+            out.append("## 共性异常指标\n")
+            for ind in common.abnormal_indicators:
+                out.append(f"- {ind.get('member','?')} - {ind.get('indicator','')}: {ind.get('value','')} {ind.get('unit','')}")
+        if self.individual:
+            out.append("\n---\n\n# 个性方案\n")
+            for mid, part in self.individual.items():
+                name = member_names.get(mid, f"成员{mid}")
+                out.append(f"\n## {name} 个性方案\n")
+                if part.overview:
+                    out.append("### 概述\n\n" + part.overview + "\n")
+                for sec in part.sections:
+                    out.append(f"### {sec.title}\n\n{sec.content}\n")
+                if part.abnormal_indicators:
+                    out.append("### 异常指标\n")
+                    for ind in part.abnormal_indicators:
+                        out.append(f"- {ind.get('member','?')} - {ind.get('indicator','')}: {ind.get('value','')} {ind.get('unit','')}")
+        return "".join(out)

+ 56 - 0
cfc-langgraph/app/models/meal.py

@@ -0,0 +1,56 @@
+from pydantic import BaseModel
+from typing import Optional, List
+
+
+class FoodRecognizeRequest(BaseModel):
+    image_url: str
+    prompt: str = "识别图片中的主要食材,返回 JSON 格式:[{name, confidence, category}]"
+
+
+class FoodsItem(BaseModel):
+    name: str
+    confidence: float
+    category: str = "unknown"
+
+
+class FoodRecognizeResponse(BaseModel):
+    foods: List[FoodsItem]
+    raw_response: str = ""
+    trace_id: str = ""
+
+
+class MenuGenerateRequest(BaseModel):
+    selected_foods: str
+    participants: str
+    date: str
+    allergies: Optional[str] = None
+    avoid_foods: Optional[str] = None
+    health_goals: Optional[str] = None
+    spice_level: Optional[int] = None
+    cuisine_pref: Optional[str] = None
+    # CR-C / AC-23:Java AiGateway 下发的午/晚餐标准菜数 D(N)。
+    # 默认 None 让旧调用方 100% 兼容;菜数硬保证在 Java normalizeMenu,此处仅软引导 prompt。
+    dish_count: Optional[int] = None
+    # 个性化食谱生成(Java 侧下发的饮食画像 / 换花样参数)。
+    # 均为可选且默认 None,旧调用方不传时行为完全不变。
+    constraints: Optional[dict] = None
+    exclude_dish_names: Optional[List[str]] = None
+    variation_seed: Optional[int] = None
+
+
+class MenuIngredient(BaseModel):
+    name: str
+    grams: int
+
+
+class MenuDish(BaseModel):
+    name: str
+    ingredients: List[MenuIngredient]
+    cooking_method: str = ""
+    nutrition: Optional[dict] = None
+    notes: str = ""
+
+
+class MenuGenerateResponse(BaseModel):
+    menu_json: str = ""
+    trace_id: str = ""

+ 29 - 0
cfc-langgraph/app/models/recommend.py

@@ -0,0 +1,29 @@
+from pydantic import BaseModel
+from typing import Optional
+
+
+class RecommendItem(BaseModel):
+    type: str  # product / activity / article
+    id: int
+    name: str
+    description: str = ""
+    cover_image: str = ""
+    price: Optional[float] = None
+    url: str = ""
+    score: float = 0.0
+    reason: str = ""
+
+
+class RecommendRequest(BaseModel):
+    user_id: int
+    query: str = ""
+    tags: list[str] = []
+    types: Optional[list[str]] = None
+    limit: int = 5
+    context: Optional[dict] = None
+
+
+class RecommendResponse(BaseModel):
+    items: list[RecommendItem]
+    source: str = ""  # sql / vector / hybrid
+    trace_id: str = ""

+ 139 - 0
cfc-langgraph/app/monitoring.py

@@ -0,0 +1,139 @@
+"""Prometheus 监控指标"""
+from prometheus_client import Counter, Histogram, Gauge, generate_latest
+from fastapi import APIRouter, Response
+import time
+import functools
+
+
+llm_calls_total = Counter(
+    "llm_calls_total", "Total LLM API calls",
+    ["model", "status"],
+)
+llm_duration_seconds = Histogram(
+    "llm_duration_seconds", "LLM call duration",
+    ["model"],
+    buckets=(0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0),
+)
+llm_tokens_total = Counter(
+    "llm_tokens_total", "Total tokens used",
+    ["model", "type"],
+)
+
+rag_retrievals_total = Counter(
+    "rag_retrievals_total", "Total RAG retrievals",
+    ["method"],
+)
+rag_duration_seconds = Histogram(
+    "rag_duration_seconds", "RAG retrieval duration",
+    ["method"],
+    buckets=(0.01, 0.05, 0.1, 0.5, 1.0),
+)
+
+agent_calls_total = Counter(
+    "agent_calls_total", "Total Agent invocations",
+    ["agent_type"],
+)
+agent_duration_seconds = Histogram(
+    "agent_duration_seconds", "Agent execution duration",
+    ["agent_type"],
+    buckets=(0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0),
+)
+
+java_calls_total = Counter(
+    "java_calls_total", "Total calls to Java backend",
+    ["endpoint", "status"],
+)
+java_duration_seconds = Histogram(
+    "java_duration_seconds", "Java backend call duration",
+    ["endpoint"],
+    buckets=(0.01, 0.05, 0.1, 0.5, 1.0, 2.0),
+)
+
+kb_sync_duration = Gauge(
+    "kb_sync_duration_seconds", "Last knowledge base sync duration"
+)
+kb_sync_documents = Gauge(
+    "kb_sync_documents_total", "Documents processed in last sync"
+)
+
+
+def monitor_agent(agent_type: str):
+    """Agent 性能监控装饰器"""
+    def decorator(func):
+        @functools.wraps(func)
+        async def wrapper(*args, **kwargs):
+            agent_calls_total.labels(agent_type=agent_type).inc()
+            start = time.perf_counter()
+            try:
+                result = await func(*args, **kwargs)
+                agent_duration_seconds.labels(agent_type=agent_type).observe(
+                    time.perf_counter() - start)
+                return result
+            except Exception as e:
+                agent_duration_seconds.labels(agent_type=agent_type).observe(
+                    time.perf_counter() - start)
+                raise
+        return wrapper
+    return decorator
+
+
+router = APIRouter(tags=["monitoring"])
+
+
+@router.get("/metrics")
+async def metrics():
+    return Response(
+        content=generate_latest(),
+        media_type="text/plain; charset=utf-8",
+    )
+
+
+@router.get("/api/v1/health")
+async def detailed_health():
+    """详细健康检查 (含组件状态)"""
+    from app.config import settings
+    status = {"status": "ok", "components": {}}
+
+    try:
+        import os
+        chroma_path = settings.chroma_db_path
+        status["components"]["chromadb"] = {
+            "status": "ok",
+            "path": chroma_path,
+            "exists": os.path.exists(chroma_path),
+        }
+    except Exception as e:
+        status["components"]["chromadb"] = {"status": "error", "message": str(e)}
+        status["status"] = "degraded"
+
+    try:
+        from langchain_openai import ChatOpenAI
+        llm = ChatOpenAI(
+            model=settings.llm_model,
+            api_key=settings.llm_api_key,
+            base_url=settings.llm_base_url,
+            max_tokens=5,
+        )
+        await llm.ainvoke("ping")
+        status["components"]["llm"] = {"status": "ok"}
+    except Exception as e:
+        status["components"]["llm"] = {"status": "error", "message": str(e)}
+        status["status"] = "degraded"
+
+    try:
+        from app.tools.java_client import JavaClient
+        client = JavaClient()
+        jc = await client._get_client()
+        resp = await jc.post("/api/admin-auth/login-by-password", json={})
+        if resp.status_code == 401:
+            status["components"]["java_backend"] = {"status": "ok", "detail": "需认证(正常)"}
+        elif resp.status_code == 200:
+            status["components"]["java_backend"] = {"status": "ok"}
+        else:
+            status["components"]["java_backend"] = {"status": "error", "code": resp.status_code, "detail": f"HTTP {resp.status_code}"}
+            status["status"] = "degraded"
+    except Exception as e:
+        status["components"]["java_backend"] = {"status": "error", "detail": str(e)}
+        status["status"] = "degraded"
+
+    return status

+ 0 - 0
cfc-langgraph/app/parsers/__init__.py


+ 954 - 0
cfc-langgraph/app/parsers/fumat_parser.py

@@ -0,0 +1,954 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+富玛特肠道微生态 16S 成人检测报告(V3.2)全量提取器
+====================================================
+
+报告格式:``fumat`` —— 北京富玛特生物科技有限公司「肠道微生态16S成人检测报告 V3.2」,
+全篇约 101 页,含 5 大类 20 余个评估章节 + 疾病/过敏相关菌明细 + 110 种检出菌。
+
+技术路线(关键设计)
+--------------------
+本报告的评估表、相关菌表、检出菌表在 PDF 里都是**真表格**(有可见框线),因此
+优先用 ``pdfplumber.find_tables()`` 做结构化抽取,而**不是**逐行正则。逐行正则
+在这份报告上会踩三个坑:
+
+  1. **跨页表格续行无标题**:110 种检出菌横跨 P25–P38、疾病相关菌横跨 P72–P88,
+     续页不再重复表头,只能靠"当前章节上下文"归组,不能靠每页找表头。
+  2. **菌名列 = 中文名 + 拉丁名粘连**:同一单元格内含 ``普拉梭菌\\nFaecalibacterium\\nprausnitzii``,
+     拉丁名本身在厂商 PDF 排版中即粘连(如 ``Escherichiacoli``,已核实原文页 30/73 即粘连),
+     属**厂商排版问题而非提取缺陷**,本提取器原样保留不做"修正"。
+  3. **风险等级单元格为空**:P16/P17 的过敏/疾病风险表只有名称、无等级值,等级实际写在
+     紧随其后的「结果提示」句子里(如"您对鸡蛋过敏、麸质敏感为中风险"),必须从
+     提示句反解,否则 17 个疾病风险等级全空。
+
+三类表头及其含义
+----------------
+- ``名称 / 评估值 / 检测结果``            → 评估项表(免疫力、营养代谢、短链脂肪酸、营养素子组)
+- ``类别 / 名称 / 评估值 / 检测结果``      → 抗生素耐药性评估
+- ``检测项目 / 检测值 / 结果评价 / 参考范围`` → 整体指标详解(1.1–1.6)
+- ``功能 / 评估值 / 参考范围 / 结果评价``   → 分项说明(1.7–7.x,共 50 余项)
+- ``菌名 / 功能说明 / 检测结果(%) / 取值范围 / 结果评价`` → 有益/中性/致病菌检出明细
+- ``菌种 / 相关性 / 检测结果 / 参考范围 / 结果评价`` → 过敏/疾病相关菌
+
+依赖:``pdfplumber``(需 CJK 字体渲染支持,``pdfminer.six`` 底层)。
+
+用法:
+    python extract_fumat_report.py <PDF路径> [输出JSON路径]
+
+**⚠️ 本文件是 vendoring 副本(2026-11-27 植入)**
+─────────────────────────────────────────
+唯一权威源:`docs/参考资料/.workbuddy/skills/bun-report-parser/scripts/extract_fumat_report.py`
+(开发侧技能脚本,本副本与源文件 MD5 一致)。
+
+由 `pdf_parser.py` 的 `detect_fumat_format()` / `_parse_fumat_report()` 调用,作为生产
+解析链路的富玛特分支。仅依赖 `pdfplumber`(与 `_parse_beijing_report` 同样在函数内延迟导入,
+本服务事实上已依赖 pdfplumber)。
+
+**同步规则**:解析逻辑修复一律改权威源,改完同步覆盖本副本并校对 MD5;不要把本副本当
+主开发副本,避免两处分叉。v3.2 报告全量 23 键解析已对基准 JSON 逐块验证通过。
+"""
+
+import os
+import re
+import json
+import sys
+
+
+# ── 指纹 ────────────────────────────────────────────────────────────
+# 命中阈值:>=5 项即判定为 fumat(这些词在标准/北京/艾德范思/谷禾报告中均不出现)
+FUMAT_FINGERPRINTS = [
+    "富玛特", "5R16S", "“管道”理论", "管道”理论", "疾病风险预测",
+    "北京富玛特", "肠道微生物健康指数", "定植抗力", "B/E比值",
+    "肠道微生物种类", "肠型", "微生态调节剂", "GAP", "菌群移植",
+]
+REPORT_ORG = "北京富玛特生物科技有限公司"
+
+# 名称异写归一
+# ------------
+# 同一疾病在不同版块写法不一致:P16 风险表写「肠易激综合症」,
+# 而小节标题与疾病介绍均写「肠易激综合征」。若不归一,「风险等级」的键与
+# 「相关疾病菌」/「疾病介绍」的分组键对不上,下游按名称 join 会漏掉这一项
+# (实测 18 个分组里只有它踩坑)。
+NAME_ALIAS = {
+    "肠易激综合症": "肠易激综合征",
+}
+
+# 比对键归一:除别名外,还要对付「合症/合征」这类同字不同形。
+# 直接 replace("症","") 对不上——「肠易激综合症」去掉「症」得「肠易激综合」,
+# 而「肠易激综合征」里根本没有「症」可去,仍是「肠易激综合征」,永不相等。
+# 故先把同义异写折叠,再连「症」「征」一起去掉当比对键。
+VARIANTS = (("综合症", "综合征"),)
+
+
+def _canon_name(name):
+    return NAME_ALIAS.get(name, name)
+
+
+def _cmp_key(s):
+    for a, b in VARIANTS:
+        s = s.replace(a, b)
+    return s.replace("症", "").replace("征", "")
+
+
+def detect_fumat(text):
+    """返回 ``(是否富玛特, 置信度, 命中指纹列表)``。
+
+    置信度 = 命中数 / 指纹总数。阈值 5 项:低于此值说明文本可能过短
+    (如只读了前 1–2 页),不足以判定。
+    """
+    hits = [fp for fp in FUMAT_FINGERPRINTS if fp in text]
+    conf = round(len(hits) / len(FUMAT_FINGERPRINTS), 3)
+    return (len(hits) >= 5, conf, hits)
+
+
+# ── 小工具 ──────────────────────────────────────────────────────────
+def _flat(s):
+    """单元格归一:换行/多空格压平为单空格,None→空串。"""
+    if s is None:
+        return ""
+    return re.sub(r"\s+", " ", str(s)).strip()
+
+
+def _num(s):
+    """尽量转数值;失败原样返回字符串。"""
+    s = _flat(s)
+    try:
+        f = float(s.replace(",", ""))
+        return int(f) if f == int(f) and "." not in s.replace(",", "") else f
+    except Exception:
+        return s
+
+
+def _cell_list(s):
+    """把单元格按换行拆成非空片段列表。"""
+    if not s:
+        return []
+    return [x.strip() for x in str(s).split("\n") if x.strip()]
+
+
+def _line_split(ln):
+    """把菌名列里的一行切成 ``(中文部分, 拉丁部分)``。
+
+    厂商把中文名与拉丁名塞进同一单元格,还要跨行、跨行首字粘连,实测有四种版式:
+
+    ┌─────────────────────┬──────────────────────┐
+    │ 单元格行              │ 切分结果              │
+    ├─────────────────────┼──────────────────────┤
+    │ ``布劳特氏菌属氢营养`` │ 中文名(换行折断)      │
+    │ ``菌Blautia``        │ 中文 ``菌`` + 拉丁      │
+    │ ``沙门氏菌Salmonella``│ 中文 ``沙门氏菌`` + 拉丁 │
+    │ ``Anaerotruncus属``   │ 拉丁开头 → 整行是中文名 │
+    └─────────────────────┴──────────────────────┘
+
+    判别口径:**行内无中文** → 整行是拉丁名续行;**拉丁字母首次出现位置之后
+    仍含中文**(如 ``Anaerotruncus属``)→ 整行是"拉丁名+中文量词"的中文显示名,
+    不拆;否则按"拉丁首现位置"切开。
+    """
+    if not re.search(r"[\u4e00-\u9fff]", ln):
+        return "", ln                      # 纯拉丁/纯数字行 → 拉丁名
+    m = re.search(r"[A-Za-z]", ln)
+    if not m:
+        return ln, ""                      # 纯中文行(含「拟杆菌(种)」式注释)
+    i = m.start()
+    head, tail = ln[:i], ln[i:]
+    if re.search(r"[\u4e00-\u9fff]", tail):
+        return ln, ""                       # 拉丁开头+中文后缀 → 中文显示名
+    return head, tail
+
+
+def _split_species(cell):
+    """把菌名/菌种单元格切成 ``(中文名, 拉丁名)``。
+
+    中文名各续行按序拼接;拉丁名各行以空格连接(如 ``Faecalibacterium`` +
+    ``prausnitzii`` → ``Faecalibacterium prausnitzii``)。
+
+    不这么拆的代价:``布劳特氏菌属氢营养菌`` 会被拆成中文名 ``布劳特氏菌属氢营养``
+    + 拉丁名 ``菌Blautia hydrogenotrophica``,中文名少了尾字「菌」,而下游按
+    菌名 join 知识库时「布劳特氏菌属氢营养」对不上「布劳特氏菌属氢营养菌」。
+    """
+    cn_parts, lat_parts = [], []
+    for ln in _cell_list(cell):
+        c, l = _line_split(ln)
+        if c:
+            cn_parts.append(c)
+        if l:
+            lat_parts.append(l)
+    return "".join(cn_parts), " ".join(lat_parts)
+
+
+HEADER_FIRST = ("名称", "类别", "检测项目", "功能", "菌名", "菌种", "种类")
+
+
+def _is_header(row):
+    """判断是否表头行(取首单元格是否等于已知表头词,避免误截数据行)。"""
+    r = row or []
+    return _flat(r[0]) in HEADER_FIRST if r else False
+
+
+def _risk_from_hint(hint, names, default=""):
+    """从「结果提示」句子里反解风险等级。
+
+    两种句式:
+      * 疾病:``您罹患便秘、结直肠癌的可能性为中风险。您罹患肥胖症的可能性为高风险。``
+      * 过敏:``您对花生过敏、坚果过敏为低风险。您对鸡蛋过敏为中风险。``
+
+    ⚠ 疾病句式含一个语法助词「的」:``...抑郁症的可能性为中风险``。若正则写成
+    ``您罹患(.+?)可能性为``,捕获组会以「的」结尾(``抑郁症的``),与风险表里的
+    ``抑郁症`` 对不上,**且恰好每组提示句的最后一项必挂**(前几项的「、」已把
+    名字切开,只有末项紧贴「的可能性」)——表现为每组等级少一条。故
+    ``(?:的)?`` 必须显式吃掉这个「的」,并再 ``rstrip("的")`` 兜底。
+
+    未提及的名称取 ``default``。返回 dict(只含最终有值或显式默认的名称)。
+    兼容异写:提示句写「肠易激综合症」而风险表/小节标题写「肠易激综合征」,
+    按 ``_cmp_key`` 折叠同义异写后比对(见该函数注释)。
+    """
+    if not hint:
+        return {n: default for n in names if default}
+    # 提示句常在页内换行(如「…抑郁症的可\n能性为中风险」),先去掉所有空白,
+    # 否则名字会被折行切断、等级反解漏项。
+    hint = re.sub(r"\s+", "", hint)
+    lvl = {}
+    found = {}
+    # 两种句式:疾病「您罹患X的可能性为Y风险」(含语法助词「的」);
+    # 过敏「您对X为Y风险」
+    for pat in (r"您罹患(.+?)(?:的)?可能性为(低风险|中风险|高风险)",
+                r"您对(.+?)(?:的)?为(低风险|中风险|高风险)"):
+        for m in re.finditer(pat, hint):
+            items = [x.strip() for x in m.group(1).split("、") if x.strip()]
+            for it in items:
+                found[it.rstrip("的")] = m.group(2)
+    for n in names:
+        n = _canon_name(n)
+        for it, lv in found.items():
+            if _cmp_key(it) == _cmp_key(n):
+                lvl[n] = lv
+                break
+    for n in list(lvl):
+        lvl[_canon_name(n)] = lvl.pop(n)
+    for n in names:
+        n = _canon_name(n)
+        if n not in lvl and default:
+            lvl[n] = default
+    return lvl
+
+
+# ── 页面载入 ────────────────────────────────────────────────────────
+def _page_lines_with_top(page):
+    """按 y 序返回 ``[(top, 行文本), ...]``。
+
+    pdfplumber 的行坐标只有从 word 上取,这里按 top 聚类重建行,供
+    「章节标题的 y 位置」定位用。
+    """
+    by_top = {}
+    for w in page.extract_words(x_tolerance=1.5, y_tolerance=3):
+        by_top.setdefault(round(w["top"], 1), []).append(w)
+    out = []
+    for top in sorted(by_top):
+        ws = sorted(by_top[top], key=lambda w: w["x0"])
+        out.append((top, "".join(w["text"] for w in ws)))
+    return out
+
+
+def _load_pages(pdf_path):
+    """返回 ``(pages_text, pages_tables, pages_lines, n_pages)``。
+
+    pages_tables[i] = ``[(top_y, [rows]), ...]`` 该页所有表(带 y 坐标);
+    pages_lines[i]  = ``[(top_y, 行文本), ...]``。
+    带 y 坐标是为了做「章节标题 y + 表格 y」的全局事件流——见 ``_walk_events``。
+    """
+    import pdfplumber
+    text, tables, lines, n = [], [], [], 0
+    with pdfplumber.open(pdf_path) as pdf:
+        n = len(pdf.pages)
+        for page in pdf.pages:
+            text.append(page.extract_text() or "")
+            lines.append(_page_lines_with_top(page))
+            tabs = []
+            for t in page.find_tables():
+                try:
+                    tabs.append((t.bbox[1], t.extract()))
+                except Exception:
+                    continue
+            tables.append(tabs)
+    return text, tables, lines, n
+
+
+def _page_text(pages_text, one_based):
+    """取第 N 页(1 起)文本。"""
+    i = one_based - 1
+    return pages_text[i] if 0 <= i < len(pages_text) else ""
+
+
+# ── 章节定位 ────────────────────────────────────────────────────────
+# 富玛特报告的章节编号 → 语义键
+OVERALL_SECTIONS = [
+    ("1.1 肠道微生物健康指数", "肠道微生物健康指数"),
+    ("1.2 肠道微生物定植抗力", "定植抗力"),
+    ("1.3 菌群多样性", "菌群多样性"),
+    ("1.4 肠型", "肠型"),
+    ("1.5 厚壁菌门/拟杆菌门", "厚壁菌拟杆菌比值"),
+    ("1.7 肠道抗炎能力", "肠道抗炎能力"),
+    ("1.8 肠道免疫力", "肠道免疫力"),
+]
+
+
+def _find_page(pages_text, pattern, start=1):
+    """返回首次命中 pattern 的页码(1 起),未命中返回 0。
+
+    关键:必须跳过目录页(P4,含「Contents 目录」)。目录页罗列了所有章节
+    标题,若不跳过,几乎每个 `_find_page("X. 章节名")` 都会命中目录页而非
+    正文页,导致后续按页取表全部为空——这是本提取器最隐蔽的一个坑。
+    """
+    for i in range(max(1, start), len(pages_text) + 1):
+        t = pages_text[i - 1]
+        if "Contents" in t and "目录" in t:
+            continue
+        if re.search(pattern, t, re.M):
+            return i
+    return 0
+
+
+def _match_top(lines_with_top, pattern):
+    """在带 y 坐标的行里找首次命中 pattern 的行,返回其 top;未命中返回 None。"""
+    rx = re.compile(pattern)
+    for top, txt in lines_with_top:
+        if rx.search(txt):
+            return top
+    return None
+
+
+def _walk_events(pages_text, pages_tables, pages_lines, defs, ncols=None,
+                 stop_pat=None):
+    """「章节标题 y + 表格 y」全局事件流,状态机归组。
+
+    为什么必须按 y 坐标而非按页归组:富玛特报告**一页常含两个小节**
+    (如 P7 同页既有「2. 肠道免疫力评估」又有「3. 营养物质代谢能力」,
+    P8 既有「4. 短链脂肪酸」又有「5.1 维生素」,P12 有「5.5」「5.6」)。
+    按页取表必然把两节混在一起——按页无法区分谁是谁的表。
+
+    做法:把每页的章节标题(按 y)与每个表格(按 y)合并成事件流,
+    按 (页码, y) 排序后顺序扫描;遇到标题切换「当前小节」,遇到表则
+    把数据行归入当前小节。同页多节由此自然分开。
+
+    ``stop_pat`` 命中的行会触发 **止位**:把当前小节清空,此后再有表
+    不再归入任何小节——否则会一路收尽本文档后面所有同列数的表
+    (如检出菌明细节之后是过敏/疾病相关菌表,同为 5 列,不清空会全部
+    误记入最后一个检出菌组)。
+
+    参数 ``defs`` = ``[(小节标题正则, 目标键名), ...]``,``ncols`` 只接受
+    列数等于它的表(None 表示不限制)。返回 ``{键名: [数据行, ...]}``。
+    """
+    stop_rx = re.compile(stop_pat) if stop_pat else None
+    events = []
+    for pg in range(1, len(pages_text) + 1):
+        t = pages_text[pg - 1]
+        if "Contents" in t and "目录" in t:      # 跳过目录页
+            continue
+        for top, txt in pages_lines[pg - 1]:
+            if stop_rx and stop_rx.search(txt):
+                events.append((pg, top, "stop", None))
+        for pat, key in defs:
+            top = _match_top(pages_lines[pg - 1], pat)
+            if top is not None:
+                events.append((pg, top, "head", key))
+        for top, rows in pages_tables[pg - 1]:
+            events.append((pg, top, "table", rows))
+    events.sort(key=lambda e: (e[0], e[1]))
+
+    acc, cur = {}, None
+    for pg, top, kind, payload in events:
+        if kind == "head":
+            cur = payload
+        elif kind == "stop":
+            cur = None
+        elif kind == "table" and cur is not None:
+            for r in payload:
+                if not r or _is_header(r):
+                    continue
+                if ncols and len(r) != ncols:
+                    continue
+                acc.setdefault(cur, []).append(r)
+    return acc
+
+
+def _all_tables_in_range(pages_tables, start, end):
+    """取出 [start, end] 页区间(1 起,闭区间)内的全部表格行,按页序展平。"""
+    out = []
+    for i in range(max(1, start), min(end, len(pages_tables)) + 1):
+        for _top, t in pages_tables[i - 1]:
+            out.extend(t)
+    return out
+
+
+def _rows_of_shape(all_rows, ncols, header_kw=None):
+    """筛出列数精确等于 ncols、且去掉了表头/残格的数据行。
+
+    本报告每类表全篇列数一致,靠「列数 + 首列非表头词」即可稳定过滤;
+    不靠每页重新找表头——跨页续表页没有表头,靠它必然断链。
+    """
+    out = []
+    for r in all_rows:
+        if not r or len(r) != ncols:
+            continue
+        if _is_header(r):
+            continue
+        out.append(r)
+    return out
+
+
+# ── 章节定义 ────────────────────────────────────────────────────────
+# 3 列表(名称/评估值/检测结果):4 个整体能力节 + 营养素 7 子组
+EVAL_DEFS = [
+    (r"^2\.\s*肠道免疫力评估", "肠道免疫力评估"),
+    (r"^3\.\s*营养物质代谢能力", "营养物质代谢能力"),
+    (r"^4\.\s*短链脂肪酸合成能力", "短链脂肪酸合成能力"),
+    (r"^6\.\s*毒素降解能力评估", "毒素降解能力评估"),
+]
+NUTRIENT_DEFS = [
+    # 5.x 编号后必须加 (?!\d) 防止 5.1 误吞 5.10/5.11;\s* 允许标题后无空格
+    (r"^5\.1(?!\d)\s*", "维生素评估"),
+    (r"^5\.2(?!\d)\s*", "天然色素合成能力"),
+    (r"^5\.3(?!\d)\s*", "氨基酸合成能力"),
+    (r"^5\.4(?!\d)\s*", "谷胱甘肽合成能力"),
+    (r"^5\.5(?!\d)\s*", "胆汁酸合成能力"),
+    (r"^5\.6(?!\d)\s*", "微量元素评估"),
+    # 注意:5.7 在 PDF 里写作「5.7 其他」,故按章节号定位而非按全名搜索
+    (r"^5\.7(?!\d)\s*", "其他神经递质及抗氧化物质"),
+]
+
+# 5 列表:检出菌明细(菌名/功能说明/检测结果/取值范围/结果评价)
+FLORA_DEFS = [
+    (r"^1\.6\.1\s*有益菌", "有益菌检出"),
+    (r"^1\.6\.2\s*中性菌", "中性菌检出"),
+    (r"^1\.6\.3\s*致病菌", "致病菌检出"),
+]
+
+# 5 列表:过敏相关菌(6 类)
+ALLERGEN_DEFS = [
+    (r"^8\.1\s*花生过敏", "花生过敏"),
+    (r"^8\.2\s*鸡蛋过敏", "鸡蛋过敏"),
+    (r"^8\.3\s*坚果过敏", "坚果过敏"),
+    (r"^8\.4\s*牛奶过敏", "牛奶过敏"),
+    (r"^8\.5\s*甲壳类和软体动物过敏", "甲壳类和软体动物过敏"),
+    (r"^8\.6\s*麸质敏感", "麸质敏感"),
+]
+
+# 5 列表:疾病相关菌(18 小节)
+DISEASE_DEFS = [
+    (r"^9\.1\s*便秘", "便秘"),
+    (r"^9\.2\s*腹泻", "腹泻"),
+    (r"^9\.3\s*炎症性肠道疾病", "炎症性肠道疾病"),
+    (r"^9\.4\s*结直肠癌", "结直肠癌"),
+    (r"^9\.5\s*肠易激综合征", "肠易激综合征"),
+    (r"^9\.6\s*克罗恩病", "克罗恩病"),
+    (r"^9\.7\s*肥胖症", "肥胖症"),
+    (r"^9\.8\s*II型糖尿病", "II型糖尿病"),
+    (r"^9\.9\s*心脑血管疾病", "心脑血管疾病"),
+    (r"^9\.10\s*甲状腺疾病", "甲状腺疾病"),
+    (r"^9\.11\s*非酒精性脂肪肝", "非酒精性脂肪肝"),
+    (r"^9\.12\s*肾脏疾病", "肾脏疾病"),
+    (r"^9\.13\s*精神分裂症", "精神分裂症"),
+    (r"^9\.14\s*抑郁症", "抑郁症"),
+    (r"^9\.15\s*阿尔茨海默病", "阿尔茨海默病"),
+    (r"^9\.16\s*帕金森", "帕金森"),
+    (r"^9\.17\s*癫痫", "癫痫"),
+    (r"^9\.18\s*自身免疫性疾病", "自身免疫性疾病"),
+]
+
+
+# ── 主入口 ──────────────────────────────────────────────────────────
+def parse(pdf_path):
+    """解析富玛特报告,返回 23 键全量 dict。"""
+    pages_text, pages_tables, pages_lines, n_pages = _load_pages(pdf_path)
+    full = "\n".join(pages_text)
+
+    ok, conf, hits = detect_fumat(full)
+    if not ok:
+        raise ValueError(
+            "非富玛特报告(指纹命中 %d/%d,%s)" % (len(hits), len(FUMAT_FINGERPRINTS), hits)
+        )
+
+    # 三趟全局事件流:一次归组、多次复用(比逐节重扫页面快且不易串味)
+    # 每趟都给定「止位」,防止该趟收尽文档后段同列数的表。
+    eval_acc = _walk_events(pages_text, pages_tables, pages_lines,
+                            EVAL_DEFS + NUTRIENT_DEFS, ncols=3,
+                            stop_pat=r"^8\.\s*肠道菌群过敏风险评估")
+    flora_acc = _walk_events(pages_text, pages_tables, pages_lines, FLORA_DEFS,
+                             ncols=5, stop_pat=r"^1\.7(?!\d)\s*")
+    # 每个检出菌组开头的「种类/总检出丰度/结果评价」3 列汇总表,单独归组取总丰度
+    flora_pct_acc = _walk_events(pages_text, pages_tables, pages_lines, FLORA_DEFS,
+                                 ncols=3, stop_pat=r"^1\.7(?!\d)\s*")
+    allergen_acc = _walk_events(pages_text, pages_tables, pages_lines, ALLERGEN_DEFS,
+                                ncols=5, stop_pat=r"^9\.1(?!\d)\s*")
+    disease_acc = _walk_events(pages_text, pages_tables, pages_lines, DISEASE_DEFS,
+                               ncols=5)
+
+    result = {
+        "文件名": os.path.basename(pdf_path),
+        "格式": "fumat",
+        "总页数": n_pages,
+        "报告机构": REPORT_ORG,
+        "指纹信息": {
+            "报告格式": "富玛特肠道微生态16S成人检测报告V3.2",
+            "命中指纹": hits,
+            "置信度": conf,
+        },
+    }
+
+    result["报告概述"] = _parse_overview(pages_text)
+    for key in ("肠道免疫力评估", "营养物质代谢能力", "短链脂肪酸合成能力",
+                "毒素降解能力评估"):
+        result[key] = _eval_result(eval_acc, key, pages_text)
+    result["抗生素耐药性评估"] = _parse_antibiotics(pages_text, pages_tables)
+    result["营养素评估"] = {
+        name: _eval_result(eval_acc, name, pages_text)
+        for _pat, name in NUTRIENT_DEFS
+        if name in eval_acc
+    }
+
+    result["肠道菌群过敏风险评估"] = _parse_allergen(pages_text, allergen_acc)
+    result["肠道菌群与疾病相关风险评估"] = _parse_disease(pages_text, disease_acc)
+
+    result["肠道微生物检测结果分析"] = _parse_overall_detail(pages_text, pages_tables)
+    for _pat, key in FLORA_DEFS:
+        result[key] = _flora_result(flora_acc, flora_pct_acc, key)
+
+    result["分项说明"] = _parse_subitems(pages_text, pages_tables)
+    result["检测结果详解"] = _parse_section_notes(pages_text, pages_tables)
+    result["肠道健康常识"] = _parse_health_knowledge(pages_text)
+
+    result["报告声明"] = _grab_block(pages_text, "报告补充说明")
+    result["免责声明"] = _grab_block(pages_text, "免责声明")
+
+    return result
+
+
+def _eval_result(acc, key, pages_text):
+    """把归组好的 3 列表行整理成 {评估项, 结果提示}。"""
+    rows = acc.get(key, [])
+    items = [{"名称": _flat(r[0]), "评估值": _flat(r[1]),
+              "检测结果": _flat(r[2]) if len(r) > 2 else ""} for r in rows]
+    return {"评估项": items,
+            "结果提示": _hint_for(pages_text, key, EVAL_DEFS + NUTRIENT_DEFS)}
+
+
+# ── 报告概述 ────────────────────────────────────────────────────────
+def _parse_overview(pages_text):
+    """P6:总体评分 / 肠道年龄评估 / 11 项整体指标。"""
+    p6 = _page_text(pages_text, _find_page(pages_text, r"肠道微生物整体健康状况") or 6)
+    out = {"肠道总体评分": None, "肠道年龄评估": {}, "整体指标": [], "结果提示": ""}
+
+    m = re.search(r"您的肠道总评分为[::]?\s*\n?\s*(\d+)", p6)
+    if m:
+        out["肠道总体评分"] = int(m.group(1))
+    for key, pat in (("肠道年龄", r"您的肠道年龄为[::]\s*(\d+)"),
+                     ("实际年龄", r"您的实际年龄为[::]\s*(\d+)"),
+                     ("年龄差值", r"年龄差值为\s*(\d+)")):
+        m = re.search(pat, p6)
+        if m:
+            out["肠道年龄评估"][key] = int(m.group(1))
+
+    # 整体指标:名称 + 值,值可能是 -0.1 / 2.2673 / 788 / 14.4304% / I
+    idx_pat = re.compile(
+        r"^(肠道微生物健康指数|肠道微生物定植抗力|肠道代谢能力评估|肠道合成能力评估|"
+        r"菌群多样性|肠道微生物种类|肠型|厚壁菌门/拟杆菌门[((]F/B[))]|有益菌|中性菌|致病菌)"
+        r"\s+(\S+)\s*$")
+    for line in p6.split("\n"):
+        line = line.strip()
+        m = idx_pat.match(line)
+        if m:
+            out["整体指标"].append(
+                {"名称": m.group(1).replace("(", "(").replace(")", ")"),
+                 "评估值": m.group(2), "检测结果": ""})
+    return out
+
+
+def _hint_at(pages_text, pg):
+    """取该页「结果提示:」后到下一个 ■/注: 前的正文。"""
+    t = _page_text(pages_text, pg)
+    m = re.search(r"结果提示[::]\s*\n?(.+?)(?=\n[■※注]\s|\Z)", t, re.S)
+    if not m:
+        return ""
+    return re.sub(r"\s+", "", m.group(1))
+
+
+# ── 抗生素耐药性 ────────────────────────────────────────────────────
+def _parse_antibiotics(pages_text, pages_tables):
+    pg = _find_page(pages_text, r"抗生素耐药性评估")
+    if not pg:
+        return {"评估项": [], "结果提示": "", "注释": ""}
+    items = []
+    cur_cat = ""
+    for r in _rows_of_shape(_all_tables_in_range(pages_tables, pg, pg + 1), 4, "类别"):
+        cat = _flat(r[0])
+        if cat:
+            cur_cat = cat
+        items.append({"类别": cur_cat, "药物": _flat(r[1]),
+                      "评估值": _flat(r[2]), "检测结果": _flat(r[3]) if len(r) > 3 else ""})
+    t = _page_text(pages_text, pg)
+    note = ""
+    m = re.search(r"注[::]\s*(.+?)(?=\s*$)", t, re.M)
+    if m:
+        note = m.group(1)
+    return {"评估项": items, "结果提示": _hint_at(pages_text, pg), "注释": note}
+
+
+def _hint_for(pages_text, key, defs):
+    """按「键名 -> 章节标题正则」反查该节的页码,取本页(必要时下一页)结果提示。"""
+    pat = next((p for p, k in defs if k == key), None)
+    pg = (_find_page(pages_text, pat) if pat else 0) \
+        or _find_page(pages_text, re.escape(key))
+    if not pg:
+        return ""
+    return _hint_at(pages_text, pg) or _hint_at(pages_text, pg + 1)
+
+
+# ── 过敏风险评估 ────────────────────────────────────────────────────
+def _parse_allergen(pages_text, grouped):
+    """风险表(名称 + 提示句反解等级)+ 归组好的相关菌(6 类 54 行)。"""
+    pg_names = _find_page(pages_text, r"8\.\s*肠道菌群过敏风险评估")
+    names, lvl, hint = [], {}, ""
+    if pg_names:
+        names = _risk_table_names(pages_text, pg_names, stop_pat=r"9\.\s*肠道菌群")
+        hint = _hint_at(pages_text, pg_names) or _hint_at(pages_text, pg_names + 1)
+        lvl = _risk_from_hint(hint, names)
+    return {"风险等级": lvl, "结果提示": hint,
+            "相关菌": {k: _corr_rows(v) for k, v in grouped.items()}}
+
+
+# ── 疾病相关风险评估 ────────────────────────────────────────────────
+def _parse_disease(pages_text, grouped):
+    """风险表(P16 尾 + P17)+ 归组好的相关菌(18 小节 198 行)+ 疾病介绍。"""
+    pg_names = _find_page(pages_text, r"9\.\s*肠道菌群与疾病相关风险评估")
+    names, lvl, hint = [], {}, ""
+    if pg_names:
+        names = _risk_table_names(pages_text, pg_names,
+                                  begin_pat=r"^9\.\s*肠道菌群")
+        # 提示句在下一页(P17)末尾
+        hint = _hint_at(pages_text, pg_names + 1) or _hint_at(pages_text, pg_names)
+        lvl = _risk_from_hint(hint, names)
+
+    intro = _disease_intros(pages_text)
+    return {"风险等级": lvl, "结果提示": hint,
+            "相关疾病菌": {k: _corr_rows(v) for k, v in grouped.items()},
+            "疾病介绍": intro}
+
+
+def _disease_intros(pages_text):
+    """按「前一个章节标题」归属每节的疾病介绍。
+
+    报告版式固定为:``[标题X][相关菌表][※][疾病介绍X][标题X+1]...``,
+    即**每个「疾病介绍」块属于其前面最近的一个章节标题**。若按"每页取第一个
+    疾病介绍"会串位——P79 页首是糖尿病的介绍(9.8 的,位于 9.9 标题之前)、
+    P75 页首是结直肠癌的介绍,都会把上一节文字安到下一节头上。
+    """
+    # 章节标题:全局按 (页, 位置) 排序
+    heads = []                       # [(page, pos, name)]
+    for _pat, name in DISEASE_DEFS:
+        pg = _find_page(pages_text, _pat)
+        if not pg:
+            continue
+        m = re.search(_pat, _page_text(pages_text, pg), re.M)
+        if m:
+            heads.append((pg, m.start(), name))
+    # 疾病介绍块:全篇扫,正文以「下一个 \n数字.数字」为界
+    intros = []                      # [(page, pos, text)]
+    for p in range(1, len(pages_text) + 1):
+        t = pages_text[p - 1]
+        for m in re.finditer(r"疾病介绍[::]\s*", t):
+            body_start = m.end()
+            nxt = re.search(r"(?=\n\d+\.\d+\s)", t[body_start:])
+            body_end = body_start + nxt.start() if nxt else len(t)
+            body = re.sub(r"\s+", " ", t[body_start:body_end]).strip()
+            if body:
+                intros.append((p, m.start(), body))
+    heads.sort(key=lambda x: (x[0], x[1]))
+    intros.sort(key=lambda x: (x[0], x[1]))
+    # 归属:每个介绍属于文档序中最后一个位于它之前的标题
+    out, idx = {}, 0
+    for ipg, ipos, text in intros:
+        cur = None
+        for hpg, hpos, hname in heads:
+            if (hpg, hpos) <= (ipg, ipos):
+                cur = hname
+            else:
+                break
+        if cur:
+            out[cur] = text
+    return out
+
+
+def _corr_rows(rows):
+    """把归组好的相关菌表行整理成 6 字段 dict 列表。"""
+    out = []
+    for r in rows:
+        if not r or len(r) < 4:
+            continue
+        cn, lat = _split_species(r[0])
+        out.append({
+            "相关性": _flat(r[1]) if len(r) > 1 else "",
+            "检测结果": _flat(r[2]) if len(r) > 2 else "",
+            "参考范围": _flat(r[3]) if len(r) > 3 else "",
+            "结果评价": _flat(r[4]) if len(r) > 4 else "",
+            "菌名": cn,
+            "拉丁名": lat,
+        })
+    return out
+
+
+def _flora_result(acc, pct_acc, key):
+    """检出菌明细 + 该组的总检出丰度。
+
+    总检出丰度来自该组开头的 3 列汇总表(种类/总检出丰度/结果评价),
+    取首列含组名(有益菌/中性菌/致病菌)那一行的次列。
+    """
+    detail = []
+    for r in acc.get(key, []):
+        if not r or len(r) < 5:
+            continue
+        cn, lat = _split_species(r[0])
+        if not cn:
+            # 拆分后中文名为空 = 该行只是上一行的拉丁名续行残片,
+            # 不是独立物种,须丢弃;否则总数虚高。
+            continue
+        detail.append({
+            "菌名": cn,
+            "拉丁名": lat,
+            "功能说明": _flat(r[1]),
+            "检测结果": _flat(r[2]),
+            "取值范围": _flat(r[3]),
+            "结果评价": _flat(r[4]) if len(r) > 4 else "",
+        })
+    grp = key.replace("检出", "")            # 有益菌/中性菌/致病菌
+    pct = ""
+    for r in pct_acc.get(key, []):
+        first = _flat(r[0])
+        val = _flat(r[1]) if len(r) > 1 else ""
+        if grp in first and val:
+            pct = val if val.endswith("%") else val + "%"
+            break
+    return {"总检出丰度": pct, "菌种明细": detail}
+
+
+def _risk_table_names(pages_text, pg, stop_pat=None, begin_pat=None):
+    """取风险表里的名称列(表体只有名称,等级为空,等级在结果提示里)。
+
+    表可能跨页(如疾病风险表 P16 尾 + P17),故从 pg 读到 stop_pat 或下一页末。
+    ``begin_pat``:同页含多个小节时(P16 同时有过敏 8. 与疾病 9. 两个风险表),
+    从命中 begin_pat 的那一行才开始收名称——否则会把上一节的名称混进来。
+    """
+    out, active, cur = [], False, pg
+    while cur <= pg + 1 and cur <= len(pages_text):
+        for raw in _page_text(pages_text, cur).split("\n"):
+            line = raw.strip()
+            if begin_pat is not None:
+                if re.search(begin_pat, line):
+                    begin_pat = None          # 已定位起点
+                    active = True
+                    out = []                  # 起点前的行(上一小节残留)全部作废
+                continue
+            if line.startswith("名称"):       # 表头行:自此开始收名称(无 begin_pat 时)
+                active = True
+                continue
+            if not active:
+                continue
+            if stop_pat and re.search(stop_pat, line):
+                return out
+            if line in ("※", "■"):       # ※ 是名称表结束标记
+                if line == "※":
+                    return out
+                continue
+            if not line:
+                continue
+            if re.match(r"^\d+$", line):
+                break
+            out.append(line)
+        cur += 1
+    return out
+
+
+# ── 整体指标详解(1.1–1.6) ─────────────────────────────────────────
+def _section_kv(pages_tables, pg, stop_pg):
+    """收集 [pg, stop_pg) 页区间内所有表的 (首列, 次列) 键值对。
+
+    同时兼容两种版式:
+      * 转置两列表(1.1 GMHI:``检测项目/肠道微生物健康指数`` ``评估值/-0.1``)
+      * 常规多列表(1.2–1.5:``检测项目 检测值 结果评价 参考范围``)
+    两种的「首列=label、次列=value」关系一致,统一处理。
+    """
+    kv = {}
+    for p in range(max(1, pg), min(stop_pg, len(pages_tables)) + 1):
+        for _top, t in pages_tables[p - 1]:
+            for r in t:
+                if not r or _is_header(r) or len(r) < 2:
+                    continue
+                k, v = _flat(r[0]), _flat(r[1])
+                if k and k not in kv:
+                    kv[k] = v
+    return kv
+
+
+def _parse_overall_detail(pages_text, pages_tables):
+    """P19–P24 的整体指标详解,输出 8 个语义键(值形状各异)。
+
+    注意各键的形状不同(有的嵌套 dict、有的裸数、有的带 % 字符串),这是
+    与上游消费方约定好的 schema,须逐个按形状组装,不能统一成一个结构。
+    """
+    out = {}
+    p_gmhi = _find_page(pages_text, r"1\.1\s*肠道微生物健康指数")
+    if not p_gmhi:
+        return out
+    p_cr = _find_page(pages_text, r"1\.2\s*肠道微生物定植抗力")
+    p_div = _find_page(pages_text, r"1\.3\s*菌群多样性")
+    p_type = _find_page(pages_text, r"1\.4\s*肠型")
+    p_fb = _find_page(pages_text, r"1\.5\s*厚壁菌门")
+
+    gm = _section_kv(pages_tables, p_gmhi, p_cr or p_gmhi + 1)
+    out["肠道微生物健康指数"] = {"GMHI": _num(gm.get("评估值", "")),
+                                 "肠道菌群状态": gm.get("肠道菌群状态", "")}
+
+    if p_cr:
+        cr = _section_kv(pages_tables, p_cr, p_div or p_cr + 1)
+        out["定植抗力"] = {"B/E比值": _num(cr.get("B/E比值", ""))}
+
+    if p_div:
+        dv = _section_kv(pages_tables, p_div, p_type or p_div + 1)
+        out["菌群多样性"] = {"多样性": _num(dv.get("肠道微生物多样性", "")),
+                             "种类数": _num(dv.get("肠道微生物种类", ""))}
+
+    if p_type:
+        stop = p_fb or (p_type + 1)
+        ty_txt = "".join(_page_text(pages_text, p) for p in range(p_type, stop + 1))
+        ty = {}
+        m = re.search(r"肠型属于[::]\s*(\S+?)\s*[,,]\s*偏向(.+?)型", ty_txt)
+        if m:
+            ty = {"肠型": m.group(1), "偏向": m.group(2)}
+        out["肠型"] = ty
+
+    if p_fb:
+        stop = _find_page(pages_text, r"1\.6\s*检出菌总览") or p_fb + 1
+        fb = _section_kv(pages_tables, p_fb, stop)
+        thick = _num(fb.get("厚壁菌门", 0))
+        bact = _num(fb.get("拟杆菌门", 0))
+        out["厚壁菌拟杆菌比值"] = {
+            "F_B比值": _num(fb.get("F/B比值", "")),
+            "厚壁菌门": thick, "拟杆菌门": bact,
+            "偏向": "厚壁菌门" if (isinstance(thick, float) and isinstance(bact, float)
+                                    and thick > bact) else "拟杆菌门"}
+
+    # 有益/中性/致病菌占比:复用三类检出菌的总检出丰度
+    for key, grp in (("有益菌占比", "有益菌"), ("中性菌占比", "中性菌"), ("致病菌占比", "致病菌")):
+        txt = _page_text(pages_text, _find_page(pages_text,
+                         re.escape("1.6." + ("1 有益菌" if grp == "有益菌" else
+                                            "2 中性菌" if grp == "中性菌" else
+                                            "3 致病菌")) ) or 0)
+        m = re.search(grp + r"\s+([\d.]+)%", txt)
+        if m:
+            out[key] = m.group(1) + "%"
+    # 与既有 schema 对齐:有益菌占比为纯数,另两项保留 % 字符串
+    if "有益菌占比" in out:
+        out["有益菌占比"] = _num(out["有益菌占比"])
+    return out
+
+
+# ── 分项说明(1.7–7.x) ─────────────────────────────────────────────
+def _parse_subitems(pages_text, pages_tables):
+    """P39–P66 的 50 余项分项说明表(功能/评估值/参考范围/结果评价)。
+
+    注意:停止页必须从 pg0 之后搜索「过敏风险评估」——直接全局搜会命中
+    P4 目录/P16 风险表,反而小于 pg0 导致区间为空、什么都抽不到。
+    """
+    out = {}
+    # 1.7 肠道抗炎能力 / 1.8 肠道免疫力 同样是 4 列表,但按约定归入
+    # 「检测结果详解」而非「分项说明」,故分项说明须从 2.1(糖)起算。
+    pg0 = _find_page(pages_text, r"2\.1\s*糖")
+    pg1 = _find_page(pages_text, r"过敏风险评估", pg0 + 1) if pg0 else 0
+    if not pg0:
+        return out
+    for pg in range(pg0, min(pg1 or len(pages_text), len(pages_tables)) + 1):
+        for _top, t in pages_tables[pg - 1]:
+            for r in t:
+                if not r or len(r) != 4 or _is_header(r):
+                    continue
+                fn = _flat(r[0]).replace("(", "(").replace(")", ")")
+                if not fn or fn in out:
+                    continue
+                intro = _intro_at(pages_text, pg, fn)
+                out[fn] = {
+                    "功能": fn, "评估值": _flat(r[1]),
+                    "参考范围": _flat(r[2]), "结果评价": _flat(r[3]),
+                    "中文名": fn, "相关介绍": intro,
+                }
+    return out
+
+
+def _intro_at(pages_text, pg, fn):
+    """取该页「相关介绍:」后的正文。"""
+    t = _page_text(pages_text, pg)
+    m = re.search(r"相关介绍[::]\s*\n?(.+?)(?=\n\d+\.\d+\s|\n[\d]+\s*$|\Z)", t, re.S)
+    return re.sub(r"\s+", " ", m.group(1)).strip() if m else ""
+
+
+# ── 检测结果详解(章节级结果提示) ───────────────────────────────────
+def _parse_section_notes(pages_text, pages_tables):
+    out = {}
+    for hdr, key in OVERALL_SECTIONS:
+        pg = _find_page(pages_text, re.escape(hdr.split(" ", 1)[0]) + r"\s*"
+                        + re.escape(hdr.split(" ", 1)[1]))
+        if not pg:
+            continue
+        out[hdr] = {"结果提示": _hint_at(pages_text, pg)}
+    return out
+
+
+# ── 肠道健康常识 ───────────────────────────────────────────────────
+def _parse_health_knowledge(pages_text):
+    out = {}
+    keys = [("管道理论", r"1\.\s*富玛特“管道”理论"),
+            ("微生态调节剂", r"2\.\s*微生态调节剂"),
+            ("健康饮食推荐", r"3\.\s*健康饮食推荐"),
+            ("肠道微生态重建与改善", r"4\.\s*肠道微生态重建与改善"),
+            ("肠道菌群移植", r"肠道菌群移植"),
+            ("FMT适应症", r"FMT适应症")]
+    for name, pat in keys:
+        pg = _find_page(pages_text, pat)
+        if pg:
+            out[name] = re.sub(r"\s+", " ", _page_text(pages_text, pg)).strip()
+    pg_ref = _find_page(pages_text, r"相关文献")
+    if pg_ref:
+        buf = []
+        for pg in range(pg_ref, min(pg_ref + 4, len(pages_text)) + 1):
+            buf.append(_page_text(pages_text, pg))
+        out["参考文献"] = re.sub(r"\s+", " ", " ".join(buf)).strip()
+    return out
+
+
+def _grab_block(pages_text, title):
+    pg = _find_page(pages_text, re.escape(title))
+    if not pg:
+        return ""
+    buf = [_page_text(pages_text, pg)]
+    if pg + 1 <= len(pages_text):
+        buf.append(_page_text(pages_text, pg + 1))
+    return re.sub(r"\s+", " ", " ".join(buf)).strip()
+
+
+# ── CLI ────────────────────────────────────────────────────────────
+def main():
+    if len(sys.argv) < 2:
+        print("用法: python extract_fumat_report.py <PDF路径> [输出JSON路径]")
+        sys.exit(1)
+    pdf_path = sys.argv[1]
+    out = sys.argv[2] if len(sys.argv) > 2 else \
+        os.path.splitext(os.path.abspath(pdf_path))[0] + ".json"
+    data = parse(pdf_path)
+    with open(out, "w", encoding="utf-8") as f:
+        json.dump(data, f, ensure_ascii=False, indent=1, default=str)
+    print("已生成: %s" % out)
+    print("指纹命中 %d/%d,置信度 %s" % (
+        len(data["指纹信息"]["命中指纹"]), len(FUMAT_FINGERPRINTS), data["指纹信息"]["置信度"]))
+
+
+if __name__ == "__main__":
+    main()

+ 2036 - 0
cfc-langgraph/app/parsers/pdf_parser.py

@@ -0,0 +1,2036 @@
+"""
+菌群报告 PDF 解析器
+从 extract_full_report_v5.py 提取核心逻辑,封装为可调用函数
+"""
+import os
+import re
+from PyPDF2 import PdfReader
+
+# === 常量 ===
+# Kangxi 部首 → CJK 统一汉字(与 extract_full_report_v5.py 完全一致)
+RADICAL_MAP = {
+    '\u2f18': '卜', '\u2f1f': '土', '\u2f24': '大', '\u2f26': '子',
+    '\u2f29': '小', '\u2f2d': '山', '\u2f32': '干', '\u2f3c': '心',
+    '\u2f42': '文', '\u2f46': '无', '\u2f4a': '木', '\u2f50': '比',
+    '\u2f54': '水', '\u2f55': '火', '\u2f5c': '牛', '\u2f5f': '玉',
+    '\u2f60': '瓜', '\u2f62': '甘', '\u2f63': '生', '\u2f64': '用',
+    '\u2f69': '白', '\u2f6a': '皮', '\u2f6c': '目', '\u2f6f': '石',
+    '\u2f75': '竹', '\u2f76': '米', '\u2f7a': '羊', '\u2f7b': '羽',
+    '\u2f7c': '老', '\u2f7f': '耳', '\u2f81': '肉', '\u2f90': '衣',
+    '\u2f95': '谷', '\u2f96': '豆', '\u2f9d': '身', '\u2fa6': '金',
+    '\u2faf': '面', '\u2fb2': '韭', '\u2fb9': '香', '\u2fca': '黑',
+    '\u2ec9': '贝', '\u2edd': '食', '\u2ee2': '马', '\u2ee5': '鱼',
+    '\u2ee8': '麦', '\u2ee9': '黄', '\u2ef0': '龙',
+    # 氏 radical U+2F52 → U+6C0F
+    '\u2f52': '氏',
+    # 以下为本项目报告 PDF 中实际出现的部首字形(U+2F00-Kangxi / U+2E80-CJK Radicals)
+    '\u2f00': '一', '\u2f04': '乙', '\u2f06': '二', '\u2f08': '人',
+    '\u2f09': '儿', '\u2f0a': '入', '\u2f0f': '几', '\u2f12': '力',
+    '\u2f17': '十', '\u2f1c': '又', '\u2f1d': '口', '\u2f20': '士',
+    '\u2f25': '女', '\u2f2b': '尸', '\u2f2f': '工', '\u2f34': '广',
+    '\u2f38': '弓', '\u2f3f': '手', '\u2f40': '支', '\u2f45': '方',
+    '\u2f47': '日', '\u2f49': '月', '\u2f4c': '止', '\u2f51': '毛',
+    '\u2f53': '气', '\u2f5a': '片', '\u2f5b': '牙', '\u2f5d': '犬',
+    '\u2f70': '示', '\u2f74': '立', '\u2f79': '网', '\u2f7d': '而',
+    '\u2f83': '自', '\u2f84': '至', '\u2f86': '舌', '\u2f8a': '色',
+    '\u2f8d': '虫', '\u2f8e': '血', '\u2f8f': '行', '\u2f94': '言',
+    '\u2f9b': '走', '\u2f9c': '足', '\u2f9f': '辛', '\u2fa5': '里',
+    '\u2fae': '非', '\u2fb0': '革', '\u2fb3': '音', '\u2fb8': '首',
+    '\u2fbc': '高', '\u2fcf': '鼠', '\u2fd0': '鼻',
+    '\u2e9f': '母', '\u2ec5': '见', '\u2ec6': '角', '\u2ed3': '长',
+    '\u2ed4': '门', '\u2ed8': '青', '\u2ed9': '韦', '\u2edb': '风',
+    '\u2ee3': '骨', '\u2eec': '齐',
+}
+
+KNOWN_MACRO = ['碳水化合物', '蛋白质', '脂肪', '纤维素', '乳制品']
+KNOWN_AMINO = ['苏氨酸', '异亮氨酸', '亮氨酸', '赖氨酸', '蛋氨酸', '胱氨酸',
+    '苯丙氨酸', '酪氨酸', '缬氨酸', '组氨酸', '丙氨酸', '丝氨酸', '甘氨酸',
+    '脯氨酸', '谷氨酸', '天门冬氨酸', '天冬氨酸', '天冬酰胺', '谷氨酰胺',
+    '精氨酸', '色氨酸']
+KNOWN_VITAMINS = ['维生素A', '维生素B1', '维生素B2', '维生素B5', '维生素B6',
+    '叶酸', '维生素B12', '维生素C', '维生素D', '维生素K2', '维生素E']
+KNOWN_TRACE = ['铁', '锌']
+KNOWN_DISEASE_RISKS = ['炎症性肠炎', '肠易激综合征', '感染性腹泻', '自闭症',
+    '抑郁症', '甲状腺疾病', '肺部感染或疾病', '自体免疫病', '结直肠癌',
+    '肥胖', '便秘', '过敏', '失眠', '肝病', '肾病', '胃病', '胆病',
+    '心脑血管疾病', 'II型糖尿病']
+KNOWN_BARRIER = ['肠道炎症水平', '肠道产气', '肠道屏障', '脂多糖LPS',
+    '次级胆汁酸', '对甲酚(p-Cresol)', '吲哚', '苯酚', '腐胺', '硫化氢', '尸胺']
+KNOWN_SCFA = ['丁酸盐(Butyrate)', '丙酸盐(Propionate)', '乙酸盐(Acetate)', '异戊酸盐(Isovaleric)']
+KNOWN_NEURO = ['血清素(5-HT)', 'γ-氨基丁酸(GABA)', '谷氨酸(Glutamate)',
+    '色氨酸(Tryptophan)', 'DOPAC', '多巴胺', '组胺(Histamine)', '一氧化氮',
+    '喹啉(Quinolinic)', '维生素K2', '肌醇(Inositol)', '肾上腺素',
+    '去甲肾上腺素', '乙酰胆碱', '皮质醇']
+KNOWN_ANTIBIOTICS = ['β-内酰胺酶类', '氨基糖苷类', '大环内酯类', '呋喃类',
+    '喹诺酮类', '磺胺类', '甲氧苄啶类', '氯霉素类', '四环素类']
+KNOWN_PATHOGENS = ['幽门螺杆菌', '艰难梭菌', '沙门氏菌', '志贺氏菌', '弯曲杆菌']
+
+# === 菌群表标题(完整版 extract_full_report_v5.py 移植) ===
+BACTERIA_TABLE_TITLES = [
+    '核心菌属构成表', '益生菌', '有害菌属构成表',
+    '其它重要菌属构成表', '病原菌属构成表',
+]
+PHYLUM_TABLE_TITLES = ['菌门构成表', '菌群门水平构成表', '门水平菌群构成']
+CLASS_TABLE_TITLES = ['菌纲构成表', '菌群纲水平构成表', '纲水平菌群构成']
+ORDER_TABLE_TITLES = ['菌目构成表', '菌群目水平构成表', '目水平菌群构成']
+FAMILY_TABLE_TITLES = ['菌科构成表', '菌群科水平构成表', '科水平菌群构成']
+GENUS_TABLE_TITLES = ['菌属构成表', '菌群属水平构成表', '属水平菌群构成']
+SPECIES_TABLE_TITLES = ['菌种构成表', '菌群种水平构成表', '种水平菌群构成']
+DISEASE_BACTERIA_TITLES = [
+    '肥胖相关菌', '便秘相关菌', '抑郁相关菌', '过敏相关菌',
+    '腹胀相关菌', '失眠相关菌', '肠道健康相关菌',
+    '多动症相关菌', '自闭症相关菌',
+]
+
+# === 食物推荐表(完整版 extract_full_report_v5.py 移植) ===
+COLUMNS_FOOD = ['名称', '分类', '推荐指数', '能量KJ', '蛋白g', '脂肪g',
+    '碳水化合物g', '淀粉g', '总膳食纤维g', '胆固醇mg']
+KNOWN_CATS = ['主食', '乳制品', '干果', '坚果', '快餐', '水产品',
+    '水果', '汤', '肉类', '蔬菜', '豆类及豆制品', '蛋类', '饮料']
+FOOD_SKIP_TEXTS = [
+    '根据您的肠道菌群', '分值从-100', '食物推荐考虑', '食物推荐是综合',
+    '需要注意的是', '本饮食推荐', '该饮食推荐根据', '后续表格中的营养',
+    '16S 高通量测序', '基于机器学习和', '肠道菌群健康检测报告说明',
+    '检测方法及局限性', '数据分析及模型', '结果解读及使用',
+    '影响因素说明', '建议将检测结果', '营养建议说明',
+    '重要提示', '推荐食物清单', '实际食用时需结合', '如有特殊疾病',
+    '免责声明', '本检测报告仅供', '以上模型预测', '正常范围的定义',
+    '募极生物',
+]
+
+
+def norm(s):
+    return ''.join(RADICAL_MAP.get(c, c) for c in s)
+
+
+def detect_format(pages_text):
+    """检测 triplet / inline 格式(v5 detect_format 移植,页面级判定)
+
+    仅当同一页同时含'疾病风险评估'+'指标范围'且存在内嵌数字的行时才算 inline,
+    否则按 triplet 处理(标准模板报告为 triplet,报告类 PDF 为 inline)。
+    """
+    for pt in pages_text:
+        t = norm(pt)
+        if '疾病风险评估' in t and '指标范围' in t:
+            for line in t.split('\n'):
+                ls = line.strip()
+                if not ls:
+                    continue
+                if re.search(r'[\u4e00-\u9fff]+\d+\.?\d*[\u4e00-\u9fff]+', ls):
+                    return 'inline'
+            return 'triplet'
+    return 'triplet'
+
+
+def extract_text(file_path):
+    """读取 PDF 并提取文本"""
+    reader = PdfReader(file_path)
+    lines = []
+    for page in reader.pages:
+        text = norm(page.extract_text() or '')
+        for line in text.split('\n'):
+            ls = line.strip()
+            if ls:
+                lines.append(ls)
+    return lines
+
+
+def _normalize_report_date(raw):
+    """将常见中文/数字日期字符串归一为 YYYY-MM-DD;无法识别返回空串。"""
+    raw = (raw or '').strip()
+    m = re.search(r'(\d{4})\s*[-/年.]\s*(\d{1,2})\s*[-/月.]\s*(\d{1,2})', raw)
+    if m:
+        return f"{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
+    return ''
+
+
+def _extract_report_date(text):
+    """从报告文本提取报告日期/采样日期/检测日期等,归一为 YYYY-MM-DD。
+
+    命中失败返回空串(保持 overview.report_date=null,不造假值)。
+    """
+    for kw in ('报告出具日期', '采样日期', '检测日期', '报告日期',
+               '采样时间', '检测时间', '报告时间'):
+        m = re.search(rf'{kw}\s*[::]?\s*(\d{{4}}\s*[-/年.]\s*\d{{1,2}}\s*[-/月.]\s*\d{{1,2}})', text)
+        if m:
+            d = _normalize_report_date(m.group(1))
+            if d:
+                return d
+    return ''
+
+
+def parse_overview(lines):
+    """提取报告概述"""
+    text = '\n'.join(lines)
+    r = {}
+    m = re.search(r'编号[::\s]*(\d+)', text)
+    if m: r['report_number'] = m.group(1)
+    m = re.search(r'姓名[::\s]*([\u4e00-\u9fff]{2,10})', text)
+    if m: r['person_name'] = re.sub(r'(编号|年龄|性别|备注|肠道).*', '', m.group(1))[:4]
+    m = re.search(r'年龄[::\s]*(\d+)', text)
+    if m: r['age'] = int(m.group(1))
+    m = re.search(r'性别[::\s]*([\u4e00-\u9fff])', text)
+    if m: r['gender'] = 'male' if m.group(1) == '男' else 'female'
+    for kw in ['健康总分', '菌群健康', '慢病控制', '营养均衡', '肠道菌群平衡',
+               '菌群多样性', '有益菌', '有害菌', '核心菌属']:
+        m = re.search(rf'{kw}\s*(\d+)', text)
+        if m: r[kw] = int(m.group(1))
+    m = re.search(r'肠道预测年龄[::\s]*([\d.]+)', text)
+    if m: r['gut_age'] = m.group(1)
+    m = re.search(r'肠型[::\s]*(\S+)', text)
+    if m: r['gut_type'] = m.group(1)
+    # V-02 fix: 补 report_date 提取(报告/采样/检测日期常见形态);无则保持 null
+    report_date = _extract_report_date(text)
+    if report_date:
+        r['report_date'] = report_date
+    return r
+
+
+def parse_triplet_until(lines, stop_markers):
+    """三元组解析:3行一组 名称/数值/状态"""
+    results = []
+    i = 0
+    while i < len(lines):
+        if any(lines[i] == sm or lines[i].startswith(sm) for sm in stop_markers):
+            break
+        if lines[i] in ('指标范围', '名称', '丰度', '评估'):
+            i += 1
+            continue
+        name = lines[i]
+        if i + 2 >= len(lines): break
+        val = lines[i + 1]
+        status = lines[i + 2]
+        if re.match(r'^-?\d+\.?\d*$', val):
+            results.append({'name': name, 'value': val, 'status': status})
+            i += 3
+        else:
+            i += 1
+    return results
+
+
+# ==========================================
+# 完整分区提取(移植自 extract_full_report_v5.py,修复分区错位)
+# 原问题:疾病风险 stop 标记缺'营养状况评估'导致吞并营养/氨基酸;
+#        维生素/微量元素标题在数据后(Case B)导致为空;屏障/SCFA/神经递质/病原菌/抗生素缺失
+# ==========================================
+
+def _extract_all_triplet(all_lines):
+    """按'指标范围'数据页标记分段提取(v5 extract_all_triplet 移植)
+
+    数据页索引约定(v5 实证):
+      data_pages[0] = 疾病风险页('疾病风险评估'标题前也有'指标范围')
+      data_pages[1] = 营养状况评估页(含前5个氨基酸:苏氨酸/异亮氨酸/亮氨酸/赖氨酸/蛋氨酸)
+      data_pages[2] = 剩余氨基酸页
+      data_pages[3] = 维生素评估页(含微量元素)
+    """
+    data_pages = []
+    for i, line in enumerate(all_lines):
+        if line == '指标范围':
+            data_pages.append(i)
+    result = {}
+
+    # 数据页1: 疾病风险评估(按已知疾病名过滤在调用方做)
+    if len(data_pages) >= 1:
+        i = data_pages[0] + 1
+        if i < len(all_lines) and all_lines[i] == '疾病风险评估':
+            i += 1
+        rows = parse_triplet_until(all_lines[i:],
+            ['主要营养评估', '氨基酸评估', '维生素评估', '微量元素评估',
+             '主要消化道致病菌', '抗生素风险评估', '抗生素耐药风险'])
+        result['disease_risks'] = [r for r in rows if '注:' not in r['name'] and '注:' not in r['name']]
+
+    # 数据页2: 营养状况评估(含前5个氨基酸)
+    if len(data_pages) >= 2:
+        i = data_pages[1] + 1
+        if i < len(all_lines) and all_lines[i] == '营养状况评估':
+            i += 1
+        rows = parse_triplet_until(all_lines[i:], ['主要营养评估', '氨基酸评估'])
+        result['nutrition_rows'] = rows[:5]
+        result['amino_p2'] = rows[5:10] if len(rows) > 5 else []
+
+    # 数据页3: 剩余氨基酸
+    if len(data_pages) >= 3:
+        i = data_pages[2] + 1
+        if i < len(all_lines) and '氨基酸' in all_lines[i]:
+            while i < len(all_lines) and '氨基酸' in all_lines[i]:
+                i += 1
+        remaining = parse_triplet_until(all_lines[i:], ['氨基酸评估'])
+        result['amino_p3'] = remaining
+
+    # 数据页4: 维生素评估 + 微量元素
+    if len(data_pages) >= 4:
+        i = data_pages[3] + 1
+        if i < len(all_lines) and all_lines[i] == '维生素评估':
+            i += 1
+        vit_rows = parse_triplet_until(all_lines[i:], ['微量元素评估', '主要消化道致病菌'])
+        vit, trace = [], []
+        for r in vit_rows:
+            if '维生素' in r['name']:
+                vit.append(r)
+            else:
+                trace.append(r)
+        result['vitamin_rows'] = vit
+        result['trace_rows'] = trace
+
+    # 主要消化道致病菌(特殊格式:致病菌/丰度%/评估)
+    for i, line in enumerate(all_lines):
+        if line == '主要消化道致病菌':
+            j = i + 1
+            while j < len(all_lines) and all_lines[j] in ('致病菌', '丰度', '评估'):
+                j += 1
+            path_rows = []
+            while j < len(all_lines) and not all_lines[j].startswith('肠道屏障'):
+                name = all_lines[j]
+                if j + 2 < len(all_lines) and re.match(r'^\d+%$', all_lines[j+1]):
+                    path_rows.append({'name': name, 'value': all_lines[j+1], 'status': all_lines[j+2]})
+                    j += 3
+                else:
+                    j += 1
+            result['pathogens'] = path_rows
+            break
+
+    # 抗生素风险评估(去重:同名只保留第一条)
+    for i, line in enumerate(all_lines):
+        if line == '抗生素风险评估':
+            abx_rows = parse_triplet_until(all_lines[i+1:], ['抗生素耐药风险', '个体化食物推荐表'])
+            seen = set()
+            deduped = []
+            for r in abx_rows:
+                n = r.get('name', '')
+                if n and n not in seen:
+                    seen.add(n)
+                    deduped.append(r)
+            result['antibiotics'] = deduped
+            break
+
+    return result
+
+
+def _extract_barrier_and_scfa_triplet(all_lines):
+    """肠道屏障及代谢物/短链脂肪酸/神经递质及激素 - 已知指标名精确匹配(v5 移植)"""
+    results = {'barrier': [], 'scfa': [], 'neurotransmitter': []}
+    current_section = None
+    i = 0
+    while i < len(all_lines):
+        line = all_lines[i]
+        if line == '肠道屏障及菌群代谢物':
+            current_section = 'barrier'
+            i += 1
+            continue
+        if '短链脂肪酸' in line:
+            current_section = 'scfa'
+            i += 1
+            continue
+        if '神经递质' in line:
+            current_section = 'neurotransmitter'
+            i += 1
+            continue
+        if current_section is None:
+            i += 1
+            continue
+
+        # 跳过头行
+        if line in ('名称', '评估值', '正常范围', '过量', '缺乏', '相关症状') or \
+           '过量 /' in line or '缺乏' in line:
+            i += 1
+            continue
+
+        # 提前终止
+        if current_section == 'barrier' and line in ('短链脂肪酸', '抗生素风险', '抗生素耐药风险'):
+            break
+        if current_section == 'scfa' and line in ('神经递质', '神经递质及激素指标', '神经递质及激素', '抗生素风险'):
+            break
+        if current_section == 'neurotransmitter' and line in ('抗生素风险', '个体化食物推荐表'):
+            break
+
+        # 只处理已知指标名
+        known = {'barrier': KNOWN_BARRIER, 'scfa': KNOWN_SCFA, 'neurotransmitter': KNOWN_NEURO}
+        known_list = known[current_section]
+        matched_name = None
+        for kn in sorted(known_list, key=len, reverse=True):
+            if line.startswith(kn) or line == kn:
+                matched_name = kn
+                break
+        if matched_name is None:
+            i += 1
+            continue
+
+        # 模式1:整行解析 名称+数值+状态+范围(inline 单行)
+        parts = line.split()
+        if len(parts) >= 2:
+            vi = None
+            for pi, p in enumerate(parts):
+                if re.match(r'^\d+$', p) and pi >= 1:
+                    vi = pi
+                    break
+            if vi:
+                val = parts[vi]
+                status = ''
+                range_ = ''
+                for rp in parts[vi+1:]:
+                    if rp in ('正常', '过多', '轻度产气', '过低', '不足', '缺乏', '不⾜'):
+                        status = rp
+                    elif re.match(r'^\d+-\d+$', rp):
+                        range_ = rp
+                results[current_section].append({
+                    'name': matched_name, 'value': val, 'status': status, 'refRange': range_
+                })
+                i += 1
+                continue
+
+        # 模式2:下一行是数值(三元组)
+        if i + 1 < len(all_lines) and re.match(r'^\d+$', all_lines[i+1]):
+            val = all_lines[i+1]
+            status = ''
+            range_ = ''
+            for j in range(2, min(6, len(all_lines)-i)):
+                if all_lines[i+j] in ('正常', '过多', '轻度产气', '过低', '不足', '缺乏', '不⾜'):
+                    status = all_lines[i+j]
+                elif re.match(r'^\d+-\d+$', all_lines[i+j]):
+                    range_ = all_lines[i+j]
+            results[current_section].append({
+                'name': matched_name, 'value': val, 'status': status, 'refRange': range_
+            })
+            i += 2
+            continue
+
+        i += 1
+
+    # 去重(每个 section 内每个指标名只保留一条)
+    for section in ('barrier', 'scfa', 'neurotransmitter'):
+        seen = set()
+        deduped = []
+        for item in results[section]:
+            n = item.get('name', '')
+            if n and n not in seen:
+                seen.add(n)
+                deduped.append(item)
+        results[section] = deduped
+
+    return results
+
+
+def _extract_names_from_region(region_str, known_names, end_pos):
+    """从区域文本中提取已知名称+数值+状态(v5 移植)"""
+    for h in ['肠道屏障及菌群代谢物名称评估值正常范围过量 / 缺乏相关症状',
+              '名称评估值正常范围过量 / 缺乏相关症状',
+              '短链脂肪酸评估值正常范围过量 / 缺乏相关症状',
+              '神经递质及激素评估值正常范围过量 / 缺乏相关症状',
+              '过量 / 缺乏相关症状']:
+        region_str = region_str.replace(h, '')
+    positions = []
+    for kn in known_names:
+        # 找所有匹配位置,选第一个后面有数字(允许空格)且不是头部标记的
+        search_start = 0
+        while True:
+            ii = region_str.find(kn, search_start)
+            if ii == -1:
+                break
+            after = region_str[ii+len(kn):ii+len(kn)+10].lstrip()
+            if re.match(r'\d', after):
+                positions.append((ii, kn))
+                break  # 找到第一个有效匹配
+            search_start = ii + 1
+    if not positions:
+        return []
+    # 去重:同名先后取前面(较精准的),不同名重叠取较长的
+    positions.sort()
+    filtered = []
+    for i, (pos, name) in enumerate(positions):
+        has_longer = False
+        for j, (pos2, name2) in enumerate(positions):
+            if i != j and pos2 <= pos and pos + len(name) <= pos2 + len(name2) and len(name2) > len(name):
+                has_longer = True
+                break
+        if not has_longer:
+            filtered.append((pos, name))
+    positions = filtered
+    seen_names = {}
+    for pos, name in positions:
+        if name not in seen_names:
+            seen_names[name] = pos
+    positions = [(pos, name) for name, pos in seen_names.items()]
+    positions.sort()
+    local = []
+    for i, (ii, kn) in enumerate(positions):
+        start_after = ii + len(kn)
+        after_text = region_str[start_after:].lstrip()
+        vm = re.match(r'(\d+(?:\.\d+)?)', after_text)
+        if not vm:
+            continue
+        val = vm.group(1)
+        whitespace_skipped = len(region_str[start_after:]) - len(after_text)
+        val_start = start_after + whitespace_skipped
+        val_end = val_start + len(val)
+        if i + 1 < len(positions):
+            next_idx = positions[i + 1][0]
+            status = region_str[val_end:next_idx].strip()
+        else:
+            status = region_str[val_end:end_pos].strip()
+        # 清理状态中的残留标记
+        status = re.sub(
+            r'注意大环内酯类|注意呋喃类|注意氯霉素类|注意喹诺酮类|注意磺胺类|'
+            r'注意甲氧苄啶类|注意四环素类|正常氨基酸评估|正常维生素评估|'
+            r'正常微量元素评估|指标范围|疾病风险评估|营养状况评估|'
+            r'抗生素风险评估|抗生素耐药风险|主要消化道致病菌',
+            '', status).strip()
+        # 截断:状态中出现'注'(如'注:本检测仅用于...')只取之前部分
+        status = re.split(r'注[::]', status)[0].strip()
+        if len(status) > 20:
+            status = status[:20]
+        local.append({'name': kn, 'value': val, 'status': status})
+    return local
+
+
+def _extract_inline_module(all_text, start_marker, end_markers, known_names):
+    """从 inline 文本中提取已知名称的指标(v5 移植)
+
+    支持两种布局:
+    A) 标题在前、数据在后(标准)
+    B) 标题在后、数据在前('指标范围'与标题之间)
+    """
+    sm_idx = all_text.find(start_marker)
+    if sm_idx == -1:
+        return []
+    end_pos = len(all_text)
+    for em in end_markers:
+        ei = all_text.find(em, sm_idx + len(start_marker))
+        if ei != -1 and ei < end_pos:
+            end_pos = ei
+
+    # Case A: 标题在前,数据在标题和 end_marker 之间
+    region_a = all_text[sm_idx:end_pos]
+    result_a = _extract_names_from_region(region_a, known_names, len(region_a))
+
+    # Case B: 标题在后,数据在'指标范围'和标题之间
+    zb_idx = all_text.rfind('指标范围', 0, sm_idx)
+    if zb_idx == -1:
+        zb_idx = max(0, sm_idx - 500)
+    region_b = all_text[zb_idx:sm_idx]
+    result_b = _extract_names_from_region(region_b, known_names, len(region_b))
+
+    # 取匹配多的那个
+    if len(result_a) >= len(result_b):
+        return result_a
+    return result_b
+
+
+def _extract_pathogens_inline(text):
+    """提取 inline 格式中主要消化道致病菌数据(幽门螺杆菌0%未检出...)"""
+    results = []
+    sidx = text.find('主要消化道致病菌')
+    if sidx == -1:
+        return results
+    eidx = text.find('肠道屏障', sidx)
+    if eidx == -1:
+        eidx = len(text)
+    region = text[sidx:eidx]
+    for name in KNOWN_PATHOGENS:
+        idx = region.find(name)
+        if idx == -1:
+            continue
+        after = region[idx + len(name):]
+        m = re.match(r'\s*(\d+%)', after)
+        if not m:
+            continue
+        abundance = m.group(1)
+        assessment_start = idx + len(name) + m.end()
+        assessment_end = len(region)
+        for next_name in KNOWN_PATHOGENS:
+            if next_name == name:
+                continue
+            ni = region.find(next_name, assessment_start)
+            if ni != -1 and ni < assessment_end:
+                assessment_end = ni
+        assessment = region[assessment_start:assessment_end].strip()
+        results.append({'name': name, 'value': abundance, 'status': assessment})
+    return results
+
+
+def _final_fallback_scan(full_text, result, section_known_map):
+    """最终的全文正则扫描——弥补所有提取器漏掉的已知指标项(v5 移植)"""
+    for section, known_list in section_known_map.items():
+        existing = {r['name'] for r in result.get(section, [])}
+        for name in known_list:
+            if name in existing:
+                continue
+            # 搜索多个变体:完整名、去掉括号的后缀
+            search_names = [name]
+            paren = name.find('(')
+            if paren != -1:
+                search_names.append(name[:paren])
+            found = False
+            for sname in search_names:
+                idx = full_text.find(sname)
+                if idx == -1:
+                    continue
+                # 跳过名称之后紧跟着的重复名称(正字+部首两次出现的情况)
+                skip = idx + len(sname)
+                while skip < len(full_text):
+                    ch = full_text[skip]
+                    if ch == '\n' or ch == ' ':
+                        skip += 1
+                    elif '\u4e00' <= ch <= '\u9fff' or '\u2f00' <= ch <= '\u2fdf':
+                        skip += 1
+                    else:
+                        break
+                after = full_text[skip:].lstrip()
+                m = re.match(r'(\d+(?:\.\d+)?)', after)
+                if not m:
+                    continue
+                val = m.group(1)
+                val_end_in_after = m.end()
+                status_raw = after[val_end_in_after:].lstrip()
+                status_m = re.search(r'([\u4e00-\u9fff/]+)', status_raw)
+                status = status_m.group(1).strip() if status_m else status_raw[:20]
+                if len(status) > 20:
+                    status = status[:20]
+                result.setdefault(section, []).append({'name': name, 'value': val, 'status': status})
+                found = True
+                break
+    return result
+
+
+def parse_report_pdf(file_path: str) -> dict:
+    """主函数:解析 PDF 返回结构化数据(v5 完整提取逻辑移植)"""
+    reader = PdfReader(file_path)
+    pages_text = [p.extract_text() or '' for p in reader.pages]
+    lines = extract_text(file_path)
+    full_text = '\n'.join(lines)
+
+    # 指纹检测:北京菌群报告
+    if detect_beijing_format(full_text):
+        return _parse_beijing_report(file_path)
+
+    fmt = detect_format(pages_text)
+    result = {'format': fmt, 'overview': parse_overview(lines)}
+
+    _SECTION_KNOWN_MAP = {
+        'disease_risks': KNOWN_DISEASE_RISKS,
+        'nutrition': KNOWN_MACRO,
+        'amino_acids': KNOWN_AMINO,
+        'vitamins': KNOWN_VITAMINS,
+        'trace_elements': KNOWN_TRACE,
+        '抗生素风险评估': KNOWN_ANTIBIOTICS,
+        '肠道屏障及代谢物': KNOWN_BARRIER,
+        '短链脂肪酸': KNOWN_SCFA,
+        '神经递质及激素': KNOWN_NEURO,
+    }
+
+    if fmt == 'triplet':
+        parsed = _extract_all_triplet(lines)
+
+        # 疾病风险评估(已知疾病名词表过滤)
+        disease_set = set(KNOWN_DISEASE_RISKS)
+        result['disease_risks'] = [r for r in parsed.get('disease_risks', []) if r['name'] in disease_set]
+        # 兜底:inline 方式补充 triplet 漏掉的项目
+        for r in _extract_inline_module(full_text, '疾病风险评估',
+                                        ['主要营养评估', '主要消化道致病菌'], KNOWN_DISEASE_RISKS):
+            if r['name'] not in {x['name'] for x in result['disease_risks']}:
+                result['disease_risks'].append(r)
+
+        # 主要营养评估
+        nutri_set = set(KNOWN_MACRO)
+        result['nutrition'] = [r for r in parsed.get('nutrition_rows', []) if r['name'] in nutri_set]
+        for r in _extract_inline_module(full_text, '营养状况评估',
+                                        ['主要营养评估', '氨基酸评估'], KNOWN_MACRO):
+            if r['name'] not in {x['name'] for x in result['nutrition']}:
+                result['nutrition'].append(r)
+
+        # 氨基酸评估(营养页内嵌 p2 + 独立页 p3 合并 + inline 兜底)
+        amino_rows = parsed.get('amino_p2', []) + parsed.get('amino_p3', [])
+        amino_set = set(KNOWN_AMINO)
+        result['amino_acids'] = [r for r in amino_rows if r['name'] in amino_set]
+        for r in _extract_inline_module(full_text, '氨基酸评估',
+                                        ['维生素评估', '主要消化道致病菌'], KNOWN_AMINO):
+            if r['name'] not in {x['name'] for x in result['amino_acids']}:
+                result['amino_acids'].append(r)
+
+        # 维生素评估 / 微量元素评估
+        vit_set = set(KNOWN_VITAMINS)
+        trace_set = set(KNOWN_TRACE)
+        result['vitamins'] = [r for r in parsed.get('vitamin_rows', []) if r['name'] in vit_set]
+        result['trace_elements'] = [r for r in parsed.get('trace_rows', []) if r['name'] in trace_set]
+        for r in _extract_inline_module(full_text, '维生素评估',
+                                        ['微量元素评估', '主要消化道致病菌'], KNOWN_VITAMINS):
+            if r['name'] not in {x['name'] for x in result['vitamins']}:
+                result['vitamins'].append(r)
+        for r in _extract_inline_module(full_text, '微量元素评估',
+                                        ['主要消化道致病菌'], KNOWN_TRACE):
+            if r['name'] not in {x['name'] for x in result['trace_elements']}:
+                result['trace_elements'].append(r)
+
+        # 主要消化道致病菌
+        result['主要消化道致病菌'] = parsed.get('pathogens', [])
+
+        # 抗生素风险评估(已知抗生素词表过滤)
+        abx_set = set(KNOWN_ANTIBIOTICS)
+        result['抗生素风险评估'] = [r for r in parsed.get('antibiotics', []) if r['name'] in abx_set]
+
+        # 肠道屏障 + 短链脂肪酸 + 神经递质(已知指标名精确匹配)
+        bs = _extract_barrier_and_scfa_triplet(lines)
+        result['肠道屏障及代谢物'] = bs['barrier']
+        result['短链脂肪酸'] = bs['scfa']
+        result['神经递质及激素'] = bs['neurotransmitter']
+        # inline 兜底补充
+        for section_key, start_mk, end_mks, known_list in [
+            ('肠道屏障及代谢物', '肠道屏障及菌群代谢物',
+             ['短链脂肪酸', '神经递质', '抗生素风险'], KNOWN_BARRIER),
+            ('短链脂肪酸', '短链脂肪酸',
+             ['神经递质', '抗生素风险'], KNOWN_SCFA),
+            ('神经递质及激素', '神经递质',
+             ['抗生素风险', '个体化食物推荐表'], KNOWN_NEURO),
+        ]:
+            existing = {r['name'] for r in result.get(section_key, [])}
+            for r in _extract_inline_module(full_text, start_mk, end_mks, known_list):
+                if r['name'] not in existing:
+                    result.setdefault(section_key, []).append(r)
+                    existing.add(r['name'])
+
+        # 最终兜底:全文正则扫描所有已知指标名
+        _final_fallback_scan(full_text, result, _SECTION_KNOWN_MAP)
+
+    else:
+        # inline 格式(v5 extract_pdf_to_json inline 分支移植)
+        result['disease_risks'] = _extract_inline_module(full_text, '疾病风险评估',
+            ['主要营养评估', '主要消化道致病菌'], KNOWN_DISEASE_RISKS)
+        result['nutrition'] = _extract_inline_module(full_text, '营养状况评估',
+            ['主要营养评估', '氨基酸评估'], KNOWN_MACRO)
+        result['amino_acids'] = _extract_inline_module(full_text, '营养状况评估',
+            ['主要营养评估', '氨基酸评估'], KNOWN_AMINO)
+        amino_p2 = _extract_inline_module(full_text, '氨基酸评估',
+            ['维生素评估', '主要消化道致病菌'], KNOWN_AMINO)
+        for a in amino_p2:
+            if a['name'] not in {x['name'] for x in result['amino_acids']}:
+                result['amino_acids'].append(a)
+        result['vitamins'] = _extract_inline_module(full_text, '维生素评估',
+            ['微量元素评估', '主要消化道致病菌'], KNOWN_VITAMINS)
+        result['trace_elements'] = _extract_inline_module(full_text, '微量元素评估',
+            ['主要消化道致病菌'], KNOWN_TRACE)
+        result['主要消化道致病菌'] = _extract_pathogens_inline(full_text)
+        result['抗生素风险评估'] = _extract_inline_module(full_text, '抗生素风险评估',
+            ['抗生素耐药风险', '个体化食物推荐表'], KNOWN_ANTIBIOTICS)
+        result['肠道屏障及代谢物'] = _extract_inline_module(full_text, '肠道屏障及菌群代谢物',
+            ['短链脂肪酸', '神经递质', '抗生素风险'], KNOWN_BARRIER)
+        result['短链脂肪酸'] = _extract_inline_module(full_text, '短链脂肪酸',
+            ['神经递质', '抗生素风险'], KNOWN_SCFA)
+        result['神经递质及激素'] = _extract_inline_module(full_text, '神经递质',
+            ['抗生素风险', '个体化食物推荐表'], KNOWN_NEURO)
+        _final_fallback_scan(full_text, result, _SECTION_KNOWN_MAP)
+
+    # 菌群检出详细列表(核心/益生菌/有害菌/病原菌 + 门纲目科属种)
+    bacteria_tables = _extract_bacteria_tables(file_path)
+    result['菌群检出详细列表'] = bacteria_tables
+
+    # 个体化食物推荐表(保留原始键名与结构)
+    food_rows, food_fmt = _extract_food_rows(file_path)
+    result['个体化食物推荐表'] = {
+        '格式': food_fmt,
+        '条目数': len(food_rows),
+        '数据': food_rows
+    }
+
+    # 统一结构:北京报告特有字段(标准报告为空)
+    result['肠道微生物健康指数'] = {}
+    result['菌群多样性'] = {}
+    result['肠道黏膜屏障'] = {}
+    result['菌群表型评估'] = {}
+    result['短链脂肪酸合成能力'] = {}
+    result['肠道菌群精准分布'] = []
+    result['营养物质及营养素代谢评估'] = {}
+    result.setdefault('抗生素风险评估', {})
+    result['毒性物质清除能力评估'] = {}
+    result['趣味肠菌评估'] = {}
+    result['胃肠道感染病原体'] = []
+    result['健康整体评估'] = {}
+    result['肠道菌群主要检测结果'] = {}
+
+    return result
+
+
+def parse_report_pdf_with_fallback(file_path: str) -> dict:
+    """算法解析 + 简单校验,返回结构化数据"""
+    result = parse_report_pdf(file_path)
+    # 简单校验:如果关键字段缺失,标记为解析不完整
+    if not result.get('overview', {}).get('overallScore') and \
+       not result.get('overview', {}).get('健康总分'):
+        result['_parse_incomplete'] = True
+    return result
+
+
+def _parse_bacteria_table(reader, pages_text, full_text, title, fmt, skip_header=False):
+    """从PDF中解析一个菌群表格(移植自 extract_full_report_v5.py)"""
+    results = []
+    sidx = full_text.find(title)
+    if sidx == -1:
+        return results
+
+    # 病原菌检出表特殊处理:找"仅列出检出的病原菌"(跳过前面的说明文字中的"病原菌")
+    if title == '病原菌':
+        better_sidx = full_text.find('仅列出检出的病原菌')
+        if better_sidx != -1:
+            sidx = better_sidx
+
+    # 找表格结束位置(下一个标题或页尾)
+    end_pos = len(full_text)
+    for t in (BACTERIA_TABLE_TITLES + PHYLUM_TABLE_TITLES + CLASS_TABLE_TITLES
+              + ORDER_TABLE_TITLES + FAMILY_TABLE_TITLES + GENUS_TABLE_TITLES
+              + SPECIES_TABLE_TITLES + DISEASE_BACTERIA_TITLES
+              + ['指标范围', '个体化食物推荐表', '报告总结', '健康总分']):
+        if t == title:
+            continue
+        ei = full_text.find(t, sidx + len(title))
+        if ei != -1 and ei < end_pos:
+            end_pos = ei
+
+    region = full_text[sidx:end_pos]
+
+    # 检测区域实际格式:如果换行数很少(<3)则是inline格式,即使全局fmt=triplet
+    lines_from_region = [l.strip() for l in region.split('\n') if l.strip()]
+    actual_fmt = fmt
+    if fmt == 'triplet' and len(lines_from_region) <= 5:
+        actual_fmt = 'inline'
+
+    if actual_fmt == 'triplet':
+        # 三元组格式:每个字段单独一行
+        lines = [l.strip() for l in region.split('\n') if l.strip()]
+        start = 0
+        for i, line in enumerate(lines):
+            if line == '名称':
+                start = i + 1
+                break
+            if line.startswith('名称'):
+                if skip_header:
+                    start = i + 1
+                break
+
+        i = start
+        while i < len(lines):
+            name = lines[i]
+            if not name or len(name) <= 1 or name in ['说明', '检测结果', '结果解释', '建议']:
+                i += 1
+                continue
+            if name.startswith('说明:') or name.startswith('改善方式'):
+                i += 1
+                continue
+            if len(name) > 80:
+                i += 1
+                continue
+
+            # 找丰度%
+            if i + 1 < len(lines) and re.match(r'^[\d]+\.?[\d]*%?$|^ND$', lines[i + 1]):
+                pct = lines[i + 1]
+                normal_range = ''
+                pop_level = ''
+                detection_rate = ''
+                desc = ''
+                j = i + 2
+                # 正常范围 (允许小数,如 0.06-6.96, 0.03-3.07)
+                if j < len(lines) and re.match(r'^[\d]+\.?[\d]*-[\d]+\.?[\d]*$', lines[j]):
+                    normal_range = lines[j]
+                    j += 1
+                # 人群水平% (允许小数,如 15.66%)
+                if j < len(lines) and re.match(r'^\d+\.?\d*%$', lines[j]):
+                    pop_level = lines[j]
+                    j += 1
+                # 检出率%
+                if j < len(lines) and re.match(r'^\d+\.?\d*%$', lines[j]):
+                    detection_rate = lines[j]
+                    j += 1
+                # 说明
+                if j < len(lines) and lines[j].startswith('说明'):
+                    desc = lines[j]
+                    j += 1
+                # 改善方式
+                if j < len(lines) and lines[j].startswith('改善方式'):
+                    if desc:
+                        desc += ' | ' + lines[j]
+                    else:
+                        desc = lines[j]
+                    j += 1
+
+                entry = {'名称': name, '丰度%': pct}
+                if normal_range:
+                    entry['正常范围%'] = normal_range
+                if pop_level:
+                    entry['人群水平%'] = pop_level
+                if detection_rate:
+                    entry['检出率%'] = detection_rate
+                if desc:
+                    entry['说明'] = desc
+                results.append(entry)
+                i = j
+            else:
+                i += 1
+    else:
+        # inline 格式
+        sample = region[:500]
+        truly_compressed = bool(re.search(r'[a-z]\d', sample, re.IGNORECASE))
+        if not truly_compressed:
+            # 有空格分隔的inline格式,使用re.finditer
+            region_clean = region
+            for hdr in ['名称', '丰度%', '正常范围%', '处于人群%水平', '%正常人有检出',
+                        '人群水平%', '%人检出']:
+                region_clean = region_clean.replace(hdr, '')
+            region_clean = re.sub(
+                r'说明:[\u4e00-\u9fff\s,。、;:,.;:()()、/a-zA-Z0-9\-]{10,}?(?=[\u4e00-\u9fff]|$)',
+                '', region_clean)
+            # 扫描所有匹配的数据行
+            for m in re.finditer(
+                    r'([\u4e00-\u9fff]{2,12}(?:[((][\u4e00-\u9fff\w]+[))])?)\s+'  # 中文名
+                    r'(?:[A-Z][a-z]+(?:\s[A-Z][a-z]+)*\s+)?'  # 可选英文名
+                    r'(ND|[\d]+\.?[\d]*%?)\s+'  # 丰度
+                    r'([\d]+\.?[\d]*-[\d]+\.?[\d]*)?\s*'  # 可选正常范围
+                    r'(\d+\.?\d*%?)\s+'  # 人群水平%
+                    r'(\d+\.?\d*%)',  # 检出率%
+                    region_clean):
+                name = m.group(1).strip()
+                pct = m.group(2)
+                if '病原菌' in name or '构成表' in name or '说明' in name or len(name) <= 1:
+                    continue
+                normal_range = m.group(3) or ''
+                pop_level = m.group(4)
+                if not pop_level.endswith('%'):
+                    pop_level += '%'
+                detection_rate = m.group(5)
+                entry = {'名称': name, '丰度%': pct}
+                if normal_range:
+                    entry['正常范围%'] = normal_range
+                entry['人群水平%'] = pop_level
+                entry['检出率%'] = detection_rate
+                results.append(entry)
+            # 模式1没有匹配时:仅中文名+丰度+人群水平(+检出率)
+            if not results:
+                for m in re.finditer(
+                        r'([\u4e00-\u9fff]{2,10}[\u4e00-\u9fff]?)\s+'
+                        r'(ND|[\d]+\.?[\d]*%?)\s+'
+                        r'(\d+\.?\d*%)\s+'
+                        r'(\d+\.?\d*%)?',
+                        region_clean):
+                    name = m.group(1).strip()
+                    pct = m.group(2)
+                    if '病原菌' in name or '构成表' in name or '说明' in name or len(name) <= 1:
+                        continue
+                    pop_level = m.group(3)
+                    detection_rate = m.group(4) or ''
+                    entry = {'名称': name, '丰度%': pct, '人群水平%': pop_level}
+                    if detection_rate:
+                        entry['检出率%'] = detection_rate
+                    results.append(entry)
+
+    return results
+
+
+def _parse_phylum_tables(reader, full_text, fmt, title_list=None):
+    """提取菌群层级构成表(门/纲/目/科/属/种 level)(移植自 extract_full_report_v5.py)"""
+    if title_list is None:
+        title_list = PHYLUM_TABLE_TITLES
+    results = []
+    for phylum_title in title_list:
+        rows = _parse_bacteria_table(reader, None, full_text, phylum_title, fmt)
+        results.extend(rows)
+    return results
+
+
+def _parse_taxonomy_levels(reader, full_text, fmt):
+    """从"菌群检出详细列表"中提取纲目科属种各级数据(移植自 extract_full_report_v5.py)"""
+    results = {}
+    sidx = full_text.find('菌群检出详细列表')
+    if sidx == -1:
+        return results
+
+    end_pos = len(full_text)
+    for t in ['个体化食物推荐表', '报告总结', '健康总分']:
+        ei = full_text.find(t, sidx)
+        if ei != -1 and ei < end_pos:
+            end_pos = ei
+
+    section = full_text[sidx:end_pos]
+
+    for level, level_name in [('纲', '菌纲构成'), ('目', '菌目构成'),
+                              ('科', '菌科构成'), ('属', '菌属构成'),
+                              ('种', '菌种构成')]:
+        marker = f'\n{level}\n名称\n丰度%'
+        marker2 = f'{level} 名称 丰度%'
+        li = section.find(marker)
+        level_start = None
+        if li == -1:
+            li2 = section.find(marker2)
+            if li2 != -1:
+                li = li2
+                level_start = li2 + len(marker2)
+            else:
+                compressed_marker = f'{level}名称丰度%人群水平%%人检出'
+                cli = section.find(compressed_marker)
+                if cli == -1:
+                    continue
+                # 压缩格式解析:用正则提取数据
+                level_start = cli + len(compressed_marker)
+                level_end = len(section)
+                for next_level in ['目', '科', '属', '种']:
+                    if next_level == level:
+                        continue
+                    ni = section.find(f'{next_level}名称丰度%人群水平%%人检出', level_start)
+                    if ni != -1 and ni < level_end:
+                        level_end = ni
+                        break
+                level_region = section[level_start:level_end]
+                compressed_pattern = re.compile(
+                    r'([\u4e00-\u9fff·]+(?:\s[\u4e00-\u9fff·]+)?\s+)?'  # 可选中文名
+                    r'([A-Za-z][A-Za-z\s.\-]*?)'  # 拉丁名(可能含空格)
+                    r'(\d+\.?\d*%)(\d+\.?\d*%)(\d+\.?\d*%)'  # 三连百分比
+                )
+                rows = []
+                for m in compressed_pattern.finditer(level_region):
+                    cn_name = (m.group(1) or '').strip()
+                    latin_name = m.group(2).strip()
+                    pct = m.group(3)
+                    pop_level = m.group(4)
+                    detection = m.group(5)
+                    name = cn_name if cn_name else latin_name
+                    entry = {'名称': name, '丰度%': pct, '人群水平%': pop_level, '检出率%': detection}
+                    rows.append(entry)
+                if rows:
+                    results[level_name] = rows
+                continue
+        else:
+            level_start = li + len(marker)
+
+        level_end = len(section)
+        for next_level in ['纲', '目', '科', '属', '种']:
+            if next_level == level:
+                continue
+            ni = section.find(f'\n{next_level}\n名称', level_start)
+            if ni != -1 and ni < level_end:
+                level_end = ni
+                break
+
+        level_region = section[level_start:level_end]
+        lines = [l.strip() for l in level_region.split('\n') if l.strip()]
+        rows = []
+        i = 0
+        while i < len(lines):
+            if lines[i] in ['名称', '丰度%', '人群水平%', '%人检出']:
+                i += 1
+                continue
+            name = lines[i]
+            if i + 2 < len(lines) and re.match(r'^[\d]+\.?[\d]*%?$', lines[i + 1]):
+                pct = lines[i + 1]
+                pop_level = lines[i + 2] if i + 2 < len(lines) else ''
+                detection = lines[i + 3] if i + 3 < len(lines) and re.match(r'^[\d.]+%$', lines[i + 3]) else ''
+                entry = {'名称': name, '丰度%': pct, '人群水平%': pop_level}
+                if detection:
+                    entry['检出率%'] = detection
+                rows.append(entry)
+                i += 4 if detection else 3
+            else:
+                i += 1
+
+        if rows:
+            results[level_name] = rows
+
+    return results
+
+
+def _extract_bacteria_tables(pdf_path):
+    """提取菌群检出详细列表,返回 {中文分组名: [行]}(移植自 extract_full_report_v5.py)
+
+    与原始脚本保持一致的文本构造与格式检测:full_text 使用
+    '\\n'.join(norm(p.extract_text()) for p in reader.pages)(不 strip、不过滤空行),
+    fmt 使用原脚本 L672-683 的独立检测逻辑。
+    """
+    reader = PdfReader(pdf_path)
+    full_text = '\n'.join(norm(p.extract_text()) for p in reader.pages)
+
+    # 原脚本 extract_bacteria_tables 的格式检测(L674-683)
+    fmt = 'triplet' if '指标范围' in full_text and '疾病风险评估' in full_text else 'inline'
+    for pt in [p.extract_text() for p in reader.pages]:
+        t = norm(pt)
+        if '疾病风险评估' in t and '指标范围' in t:
+            for line in t.split('\n'):
+                if re.search(r'[\u4e00-\u9fff]+\d+\.?\d*[\u4e00-\u9fff]+', line.strip()):
+                    fmt = 'inline'
+                    break
+            break
+
+    all_tables = {}
+
+    # 核心菌属构成表1-3
+    core_genus = []
+    for i in range(1, 4):
+        title = f'核心菌属构成表{i}'
+        rows = _parse_bacteria_table(reader, None, full_text, title, fmt)
+        core_genus.extend(rows)
+    all_tables['核心菌属'] = core_genus
+
+    # 益生菌(使用更精确的表头定位,跳过前面的说明文字)
+    prob_marker = '仅列出丰度前22的益生菌种'
+    prob_sidx = full_text.find(prob_marker)
+    if prob_sidx != -1:
+        prob_rows = _parse_bacteria_table(reader, None, full_text, prob_marker, fmt, skip_header=True)
+    else:
+        prob_rows = _parse_bacteria_table(reader, None, full_text, '益生菌', fmt, skip_header=True)
+    all_tables['益生菌'] = [r for r in prob_rows if r.get('名称') and r['名称'] not in
+                            ['我的益生菌都为ND', '仅列出丰度前22的益生菌种。']]
+
+    # 有害菌属构成表1-2
+    harmful = []
+    for i in range(1, 3):
+        title = f'有害菌属构成表{i}'
+        rows = _parse_bacteria_table(reader, None, full_text, title, fmt)
+        harmful.extend(rows)
+    all_tables['有害菌属'] = harmful
+
+    # 其它重要菌属
+    other_rows = _parse_bacteria_table(reader, None, full_text, '其它重要菌属构成表', fmt)
+    all_tables['其它重要菌属'] = other_rows
+
+    # 病原菌属构成表
+    patho_genus = _parse_bacteria_table(reader, None, full_text, '病原菌属构成表', fmt)
+    all_tables['病原菌属'] = patho_genus
+
+    # 病原菌(检出列表)
+    patho_rows = _parse_bacteria_table(reader, None, full_text, '病原菌', fmt, skip_header=True)
+    all_tables['病原菌检出'] = [r for r in patho_rows if r.get('名称') and len(r['名称']) >= 2
+                               and '仅列出' not in r['名称'] and '说明' not in r['名称']]
+
+    # 菌门构成表(phylum level)
+    phylum_rows = _parse_phylum_tables(reader, full_text, fmt)
+    if phylum_rows:
+        all_tables['菌门构成'] = phylum_rows
+
+    # 菌纲构成表
+    class_rows = _parse_phylum_tables(reader, full_text, fmt, CLASS_TABLE_TITLES)
+    if class_rows:
+        all_tables['菌纲构成'] = class_rows
+
+    # 菌目构成表
+    order_rows = _parse_phylum_tables(reader, full_text, fmt, ORDER_TABLE_TITLES)
+    if order_rows:
+        all_tables['菌目构成'] = order_rows
+
+    # 菌科构成表
+    family_rows = _parse_phylum_tables(reader, full_text, fmt, FAMILY_TABLE_TITLES)
+    if family_rows:
+        all_tables['菌科构成'] = family_rows
+
+    # 菌属构成表
+    genus_rows = _parse_phylum_tables(reader, full_text, fmt, GENUS_TABLE_TITLES)
+    if genus_rows:
+        all_tables['菌属构成'] = genus_rows
+
+    # 菌种构成表
+    species_rows = _parse_phylum_tables(reader, full_text, fmt, SPECIES_TABLE_TITLES)
+    if species_rows:
+        all_tables['菌种构成'] = species_rows
+
+    # 菌群层级(纲目科属种)- 从"菌群检出详细列表"统一入口提取
+    taxonomy_rows = _parse_taxonomy_levels(reader, full_text, fmt)
+    for key, rows in taxonomy_rows.items():
+        if rows:
+            all_tables[key] = rows
+
+    return all_tables
+
+
+def split_7_fields(s):
+    """将压缩数字串切分为 7 个字段(移植自 extract_full_report_v5.py)"""
+    results = []
+    ranges = [(2, 4), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 4)]
+
+    def backtrack(pos, idx, nums):
+        if idx == 7:
+            if pos == len(s):
+                results.append(list(nums))
+            return
+        if pos >= len(s):
+            return
+        lo, hi = ranges[idx]
+        for w in range(lo, min(hi + 1, len(s) - pos + 1)):
+            chunk = s[pos:pos + w]
+            if chunk.isdigit():
+                backtrack(pos + w, idx + 1, nums + [int(chunk)])
+
+    backtrack(0, 0, [])
+    return results
+
+
+def decode_compressed(name, num_str, ref_vals=None):
+    """解码压缩食物数字串(移植自 extract_full_report_v5.py)"""
+    raw = num_str.lstrip('-')
+    has_neg = num_str.startswith('-')
+    candidates = []
+    for rec_len in range(1, 3):
+        if rec_len > len(raw):
+            continue
+        rec = ('-' if has_neg else '') + raw[:rec_len]
+        try:
+            rec_val = int(rec)
+            if not (-100 <= rec_val <= 100):
+                continue
+        except Exception:
+            continue
+        remain = raw[rec_len:]
+        for nums in split_7_fields(remain):
+            if ref_vals:
+                matches = sum(1 for i in range(7) if ref_vals[i] == nums[i])
+                if matches >= 6:
+                    candidates.append([rec_val] + nums)
+            else:
+                candidates.append([rec_val] + nums)
+    if not candidates:
+        return None
+    if ref_vals:
+        candidates.sort(key=lambda r: (sum(1 for i in range(7) if ref_vals[i] == r[1:][i]),
+                                       -len(str(abs(r[0])))), reverse=True)
+        if sum(1 for i in range(7) if ref_vals[i] == candidates[0][1:][i]) < 6:
+            return None
+    else:
+        candidates.sort(key=lambda r: (len(str(abs(r[0]))),
+                                       -sum(1 for i in range(7) if r[1:][i] == 0)))
+    return candidates[0]
+
+
+def extract_food_table(pdf_path, ref_lookup=None):
+    """提取个体化食物推荐表(移植自 extract_full_report_v5.py)"""
+    reader = PdfReader(pdf_path)
+    food_start = None
+    for i, page in enumerate(reader.pages):
+        if '个体化食物推荐表' in page.extract_text():
+            food_start = i
+            break
+    if food_start is None:
+        return [], 'not_found'
+
+    first_text = norm(reader.pages[food_start + 1].extract_text())
+    lines = [l.strip() for l in first_text.split('\n')
+             if l.strip() and not re.match(r'\d+/\d+', l)]
+    # 判断压缩格式:任何一行超过100字符(单行密集格式),或前10行中超过3行长行
+    is_compressed = (len(lines) >= 1 and any(len(l) > 100 for l in lines[:10])) or \
+                    sum(1 for l in lines[:10] if len(l) > 100) >= 2
+
+    rows = []
+    if is_compressed:
+        fmt = 'compressed'
+        for i in range(food_start + 1, len(reader.pages)):
+            text = norm(reader.pages[i].extract_text())
+            text = re.sub(r'\d+/\d+', '', text)
+            header = '名称分类推荐指数能量KJ蛋白g脂肪g碳水化合物g淀粉g总膳食纤维g胆固醇mg'
+            text = text.replace(header, '')
+            for kw in FOOD_SKIP_TEXTS:
+                text = text.replace(kw, '')
+            while text:
+                best_cat, best_idx = None, len(text)
+                for cat in KNOWN_CATS:
+                    idx = text.find(cat)
+                    if idx != -1 and idx < best_idx:
+                        best_idx, best_cat = idx, cat
+                if best_cat is None:
+                    break
+                name = text[:best_idx]
+                text = text[best_idx + len(best_cat):]
+                num_str = ''
+                while text and (text[0].isdigit() or text[0] in '-\u2212\u2014'):
+                    c = '-' if text[0] in '\u2212\u2014' else text[0]
+                    num_str += c
+                    text = text[1:]
+                if not name or not num_str:
+                    continue
+                ref_vals = ref_lookup.get(name) if ref_lookup else None
+                decoded = decode_compressed(name, num_str, ref_vals)
+                if decoded:
+                    rows.append(dict(zip(COLUMNS_FOOD, [name, best_cat] + [str(v) for v in decoded])))
+    else:
+        fmt = 'vertical'
+        all_lines = []
+        for i in range(food_start + 1, len(reader.pages)):
+            for line in norm(reader.pages[i].extract_text()).split('\n'):
+                lt = line.strip()
+                if not lt or re.match(r'\d+/\d+', lt) or lt in COLUMNS_FOOD:
+                    continue
+                if len(lt) > 60 and any(k in lt for k in FOOD_SKIP_TEXTS):
+                    continue
+                all_lines.append(lt)
+        i = 0
+        while i + 9 < len(all_lines):
+            name = all_lines[i].strip()
+            cat = all_lines[i + 1].strip()
+            if cat not in KNOWN_CATS:
+                i += 1
+                continue
+            nums = []
+            ok = True
+            for j in range(2, 10):
+                v = all_lines[i + j].replace('\u2212', '-').replace('\u2014', '-').strip()
+                try:
+                    int(v)
+                    nums.append(v)
+                except Exception:
+                    ok = False
+                    break
+            if ok and len(nums) == 8:
+                rows.append(dict(zip(COLUMNS_FOOD, [name, cat] + nums)))
+            i += 1
+    return rows, fmt
+
+
+def _extract_food_rows(pdf_path):
+    """食物推荐表解析:优先复用同目录其他报告的参考营养表做压缩格式解码"""
+    ref_nutrition = {}
+    base_dir = os.path.dirname(pdf_path) or '.'
+    for fname in sorted(os.listdir(base_dir)):
+        if fname.lower().endswith('.pdf') and fname != os.path.basename(pdf_path):
+            try:
+                tr, _ = extract_food_table(os.path.join(base_dir, fname))
+                if len(tr) > 100:
+                    for r in tr:
+                        ref_nutrition[r['名称']] = [int(r[k]) for k in
+                            ['能量KJ', '蛋白g', '脂肪g', '碳水化合物g', '淀粉g',
+                             '总膳食纤维g', '胆固醇mg']]
+                    break
+            except Exception:
+                continue
+    food_rows, food_fmt = extract_food_table(pdf_path, ref_nutrition or None)
+    return food_rows, food_fmt
+
+
+# ============================================================
+# 北京菌群报告 — 指纹检测
+# ============================================================
+
+FINGERPRINTS_BEIJING = [
+    "肠道微生物健康指数",
+    "GMHI",
+    "肠道菌群主要检测结果",
+    "核心菌属综合评分",
+    "有益菌综合评分",
+    "有害菌综合评分",
+    "肠道菌群精准分布",
+    "营养物质及营养素代谢评估",
+    "趣味肠菌评估",
+    "高通量测序",
+]
+
+
+def detect_beijing_format(text):
+    """检测是否为北京菌群报告格式"""
+    beijing_matches = sum(1 for f in FINGERPRINTS_BEIJING if f in text)
+    if beijing_matches >= 3:
+        return True
+    return False
+
+
+# ============================================================
+# 北京菌群报告 — 章节提取(PyPDF2 版)
+# ============================================================
+
+# 疾病风险关键词(北京报告特有)
+DISEASE_KEYWORDS_BJ = [
+    "溃疡性结肠炎", "克罗恩病", "腹泻型肠易激综合征",
+    "硬化性胆管炎", "非酒精性脂肪性肝病", "肝硬化",
+    "便秘", "IgA肾病", "肾结石", "格雷夫斯病",
+    "慢性淋巴细胞性甲状腺炎", "强直性脊柱炎",
+    "精神分裂症", "痛经",
+    "结直肠癌", "胃癌", "甲状腺癌", "肺癌", "乳腺癌",
+    "高血压", "冠心病", "2型糖尿病", "高脂血症",
+    "食管癌", "胆结石", "哮喘", "心脏病",
+    "膜性肾病", "帕金森病", "类风湿关节炎",
+]
+
+# 抗生素分类(北京报告格式)
+ANTIBIOTIC_CATEGORIES_BJ = [
+    "β内酰胺类", "氨基糖苷类", "大环内酯类", "四环素类",
+    "氯霉素类", "磺酰胺类", "喹诺酮类", "万古霉素类",
+    "头孢菌素类", "磷霉素类", "甲氧苄氨嘧啶类",
+    "N-乙酰基转移酶类", "O-磷酸转移酶类", "16S甲基转移酶",
+]
+
+# 核心菌属 22 种(北京报告)
+CORE_GENERA_BJ = [
+    ("阿克曼菌属", "Akkermansia"), ("另枝菌属", "Alistipes"),
+    ("拟杆菌属", "Bacteroides"), ("双歧杆菌属", "Bifidobacterium"),
+    ("布劳特氏菌属", "Blautia"), ("梭菌属", "Clostridium"),
+    ("粪球菌属", "Coprococcus"), ("戴阿利斯特杆菌属", "Dialister"),
+    ("多尔氏菌属", "Dorea"), ("真杆菌属", "Eubacterium"),
+    ("粪杆菌属", "Faecalibacterium"), ("Lachnoclostridium属", "Lachnoclostridium"),
+    ("毛螺菌属", "Lachnospira"), ("乳杆菌属", "Lactobacillus"),
+    ("巨单胞菌属", "Megamonas"), ("颤螺旋菌属", "Oscillospira"),
+    ("副拟杆菌属", "Parabacteroides"), ("考拉杆菌属", "Phascolarctobacterium"),
+    ("普雷沃氏菌属", "Prevotella"), ("罗氏菌属", "Roseburia"),
+    ("瘤胃球菌属", "Ruminococcus"), ("萨特氏菌属", "Sutterella"),
+]
+
+# 病原体列表(北京报告)
+PATHOGEN_LIST_BJ = [
+    "气单胞菌属", "蜡样芽孢杆菌", "唐菖蒲伯克霍尔德氏菌",
+    "弯曲杆菌属", "艰难梭菌", "肉毒梭菌", "产气荚膜梭菌",
+    "幽门螺杆菌", "肺炎克雷伯菌", "类志贺邻单胞菌",
+    "沙门氏菌属", "志贺氏菌属", "金黄色葡萄球菌",
+    "肺炎链球菌", "霍乱弧菌", "拟态弧菌", "副溶血弧菌",
+    "小肠结肠炎耶尔森氏菌", "假结核耶尔森氏菌",
+]
+
+
+def _find_content_after_toc(text):
+    """找到北京报告中 TOC 之后的内容起始位置"""
+    # 找"第一部分 健康整体评估"后的内容,或者"健康整体评估"正文
+    markers = ['第一部分 健康整体评估', '菌群得分总览', '您属于肠']
+    for m in markers:
+        idx = text.find(m)
+        if idx != -1:
+            return idx
+    return 0
+
+
+def _find_last_section(text, section_title):
+    """找到章节标题的最后一次出现(实际内容,非目录)"""
+    last = -1
+    start = 0
+    while True:
+        idx = text.find(section_title, start)
+        if idx == -1:
+            break
+        last = idx
+        start = idx + 1
+    return last
+
+
+def _parse_bj_gmhi(text):
+    """提取 GMHI 肠道微生物健康指数(从内容区提取)"""
+    gmhi = {}
+    # 找最后一次出现的 GMHI 值(内容区,非目录)
+    content_start = _find_content_after_toc(text)
+    content = text[content_start:]
+
+    m = re.search(r'GMHI[)\)]?[为是](\d+)', content)
+    if m: gmhi['GMHI'] = float(m.group(1))
+    m = re.search(r'肠道微生物健康指数[为](\d+)', content)
+    if m: gmhi['肠道微生物健康指数'] = float(m.group(1))
+    m = re.search(r'肠道菌群状态[为::\s]*(\S+?)[。,\n]', content)
+    if m: gmhi['肠道菌群状态'] = m.group(1)
+
+    # 健康状态推断
+    if gmhi.get('肠道微生物健康指数') or gmhi.get('GMHI'):
+        score = gmhi.get('肠道微生物健康指数') or gmhi.get('GMHI', 0)
+        if score >= 90: gmhi['健康状态'] = '健康'
+        elif score >= 80: gmhi['健康状态'] = '健康倾向'
+        elif score >= 40: gmhi['健康状态'] = '亚健康'
+        elif score >= 20: gmhi['健康状态'] = '不健康倾向'
+        else: gmhi['健康状态'] = '不健康'
+    return gmhi
+
+
+def _parse_bj_gut_type(text):
+    """提取肠型"""
+    content_start = _find_content_after_toc(text)
+    content = text[content_start:]
+    m = re.search(r'属于\s*肠[型道]\s*([IVX]+)', content)
+    if m: return f'肠型{m.group(1)}'
+    m = re.search(r'属于\s*肠[型道]\s*(\S+?)[,。,.\n]', content)
+    if m: return m.group(1).strip()
+    return None
+
+
+def _parse_bj_balance(text):
+    """提取肠道菌群平衡评估"""
+    m = re.search(r'(I{1,3}度失衡)', text)
+    if m: return m.group(1)
+    return None
+
+
+def _parse_bj_barrier(text):
+    """提取肠道黏膜屏障/BE比值"""
+    barrier = {}
+    # 在内容区找表格
+    content_start = _find_content_after_toc(text)
+    content = text[content_start:]
+    # 找 BE比值 表格行
+    m = re.search(r'BE比[值例][::\s]*(\d+\.?\d*)', text)
+    if m: barrier['BE比值'] = float(m.group(1))
+    m = re.search(r'双歧杆菌[属菌][::\s]*(\d+\.?\d*)', text)
+    if m: barrier['双歧杆菌属'] = float(m.group(1))
+    m = re.search(r'肠杆菌[科属][::\s]*(\d+\.?\d*)', text)
+    if m: barrier['肠杆菌科'] = float(m.group(1))
+    # 综合评估在"BE比值"附近找
+    be_idx = content.find('BE比')
+    if be_idx != -1:
+        chunk = content[be_idx:be_idx + 300]
+        m = re.search(r'(正常|轻度损伤|中度损伤|重度损伤|损伤)', chunk)
+        if m: barrier['综合评估'] = m.group(1)
+    return barrier
+
+
+def _parse_bj_diversity(text):
+    """提取菌群多样性"""
+    div = {}
+    content_start = _find_content_after_toc(text)
+    content = text[content_start:]
+    m = re.search(r'多样性指数[为](\d+\.?\d*)', content)
+    if m: div['Shannon指数'] = float(m.group(1))
+    m = re.search(r'高于[::\s]*(\d+)%', content)
+    if m: div['人群百分位'] = f'高于{m.group(1)}%'
+    m = re.search(r'菌种总数[::\s]*(\d+)', content)
+    if m: div['菌种总数'] = int(m.group(1))
+    return div
+
+
+def _parse_bj_phenotype(text):
+    """提取菌群表型评估"""
+    pheno = {}
+    # 找表型评估表格区域
+    last_idx = _find_last_section(text, '菌群表型评估')
+    if last_idx == -1:
+        last_idx = _find_last_section(text, '肠道菌群表型评估')
+    if last_idx == -1:
+        return pheno
+    # 取表格区域
+    region = text[last_idx:last_idx + 1500]
+    # 解析表格行: 指标名 评估值 结果
+    for label, kw in [('革兰氏阳性菌', '阳性菌'), ('革兰氏阴性菌', '阴性菌'),
+                       ('生物膜合成', '生物膜'), ('好氧菌', '好氧'),
+                       ('厌氧菌', '厌氧'), ('兼性厌氧菌', '兼性'),
+                       ('氧化胁迫耐受', '氧化'), ('致病潜力', '致病')]:
+        # 找该行: 值在指标名附近
+        idx = region.find(kw)
+        if idx == -1:
+            continue
+        chunk = region[idx:idx + 100]
+        val_m = re.search(r'(\d+\.?\d*)', chunk)
+        if val_m:
+            entry = {'评估值': float(val_m.group(1))}
+            for status in ['正常', '异常']:
+                if status in chunk:
+                    entry['结果'] = status
+                    break
+            pheno[label] = entry
+    return pheno
+
+
+def _parse_bj_scfa(text):
+    """提取短链脂肪酸合成能力"""
+    scfa = {}
+    # 找 SCFA 表格区域(最后一次出现)
+    last_idx = _find_last_section(text, '短链脂肪酸合成能力')
+    if last_idx == -1:
+        last_idx = _find_last_section(text, '短链脂肪酸')
+    if last_idx == -1:
+        return scfa
+    region = text[last_idx:last_idx + 800]
+    for acid in ['甲酸', '乙酸', '丙酸', '丁酸', '戊酸', '己酸']:
+        m = re.search(rf'{acid}[^a-zA-Z]*?(\d+)', region)
+        if m:
+            scfa[acid] = int(m.group(1))
+    return scfa
+
+
+def _parse_bj_core_bacteria(text):
+    """提取核心菌属精准分布"""
+    bacteria = []
+    for cn_name, lat_name in CORE_GENERA_BJ:
+        idx = text.find(lat_name)
+        if idx == -1: idx = text.find(cn_name)
+        if idx == -1: continue
+        chunk = text[max(0, idx - 50):idx + 200]
+        val_m = re.search(r'(\d+\.?\d*)', chunk)
+        status_m = re.search(r'(缺失|严重超标|超标|偏低|正常)', chunk)
+        pct_m = re.search(r'(\d+\.?\d*)%', chunk)
+        range_m = re.search(r'([\d.]+-[\d.]+)', chunk)
+        entry = {
+            '拉丁名': lat_name,
+            '中文名': cn_name,
+            '检测结果': float(val_m.group(1)) if val_m else None,
+            '状态': status_m.group(1) if status_m else '未知',
+            '人群百分位': float(pct_m.group(1)) if pct_m else None,
+            '参考范围': range_m.group(1) if range_m else None,
+        }
+        bacteria.append(entry)
+    return bacteria
+
+
+def _parse_related_bacteria_in_chunk(chunk):
+    """从文本片段提取关联菌列表(如:乳杆菌属(缺乏)、另枝菌属(超标))"""
+    bacteria = []
+    for bm in re.finditer(
+            r'([\u4e00-\u9fa5]{2,10}?(?:菌|属|科|杆菌|球菌|梭菌))[((]\s*(超标|缺乏|偏高|偏低|异常|正常)\s*[))]',
+            chunk):
+        bacteria.append({
+            'bacteria': bm.group(1),
+            'correlation': bm.group(2),
+            'value': '',
+            'status': '',
+        })
+    return bacteria
+
+
+def _parse_bj_disease_risks(text):
+    """提取疾病风险评估(含关联菌 P0)"""
+    diseases = []
+    for keyword in DISEASE_KEYWORDS_BJ:
+        idx = text.find(keyword)
+        if idx == -1: continue
+        chunk = text[idx:idx + 200]
+        val_m = re.search(r'(\d+\.\d+)', chunk)
+        level_m = re.search(r'(低风险|较低风险|中度风险|较高风险|高风险)', chunk)
+        if val_m:
+            entry = {
+                '疾病': keyword,
+                '风险指数': float(val_m.group(1)),
+                '风险等级': level_m.group(1) if level_m else '',
+            }
+            bacteria = _parse_related_bacteria_in_chunk(chunk)
+            if bacteria:
+                entry['related_bacteria'] = bacteria
+            diseases.append(entry)
+
+    # 补充:从「疾病肠菌评估(异常项)」章节提取关联菌,按疾病名匹配补挂
+    ab_idx = text.find('疾病肠菌评估')
+    if ab_idx != -1:
+        ab_sec = text[ab_idx:ab_idx + 1800]
+        for entry in diseases:
+            if entry.get('related_bacteria'):
+                continue
+            kw_idx = ab_sec.find(entry['疾病'])
+            if kw_idx == -1:
+                continue
+            # 截断到下一个疾病关键字,避免跨疾病串扰
+            end = len(ab_sec)
+            for other in DISEASE_KEYWORDS_BJ:
+                if other == entry['疾病']:
+                    continue
+                oi = ab_sec.find(other, kw_idx + len(entry['疾病']))
+                if oi != -1 and oi < end:
+                    end = oi
+            chunk = ab_sec[kw_idx:end]
+            bacteria = _parse_related_bacteria_in_chunk(chunk)
+            if bacteria:
+                entry['related_bacteria'] = bacteria
+    return diseases
+
+
+def _parse_bj_nutrient_metabolism(text):
+    """提取营养物质及营养素代谢评估"""
+    metabolism = {}
+    # 主要营养物质
+    for n in ['碳水化合物', '蛋白质', '脂肪', '矿物质']:
+        m = re.search(rf'{n}[^估]*?(\d+)', text)
+        if m:
+            metabolism.setdefault('主要营养物质代谢', {})[n] = int(m.group(1))
+    # 糖类
+    for item in ['葡萄糖(糖酵解途径)', '葡萄糖(磷酸戊糖途径)', '果糖和甘露糖',
+                 '半乳糖', '淀粉和蔗糖', '氨基糖和核苷酸糖', '丙酮酸']:
+        m = re.search(rf'{item[:4]}.*?(\d+)', text)
+        if m:
+            metabolism.setdefault('糖类代谢', {})[item] = int(m.group(1))
+    # 脂类
+    for item in ['甘油酯', '甘油磷脂', '甘油三酯', '鞘脂类', '脂肪酸',
+                 '硬脂酸', '棕榈酸', '花生四烯酸', '二十二碳六烯酸',
+                 'Omega-3', 'Omega-6']:
+        m = re.search(rf'{item}.*?(\d+)', text)
+        if m:
+            metabolism.setdefault('脂类代谢', {})[item] = int(m.group(1))
+    # 维生素
+    for item in ['维生素A', '维生素B1', '维生素B2', '维生素B3', '维生素B5',
+                 '维生素B6', '维生素B7', '维生素B12', '维生素C', '维生素D',
+                 '维生素E', '维生素K1', '维生素K2', '维生素K3', '叶酸']:
+        m = re.search(rf'{item}.*?(\d+)', text)
+        if m:
+            metabolism.setdefault('维生素', {})[item] = int(m.group(1))
+    # 微量元素
+    for item in ['铁', '锌', '钙', '镁', '硒', '锰', '铜', '钴', '镍', '钼', '铬', '钒']:
+        m = re.search(rf'{item}[^估]*?(\d+)', text)
+        if m:
+            metabolism.setdefault('微量元素', {})[item] = int(m.group(1))
+    # 氨基酸
+    for item in ['赖氨酸', '丝氨酸', '亮氨酸', '色氨酸', '苯丙氨酸',
+                 '缬氨酸', '组氨酸', '半胱氨酸', '酪氨酸', '丙氨酸',
+                 '脯氨酸', '苏氨酸', '谷氨酸', '异亮氨酸', '精氨酸',
+                 '蛋氨酸', '甘氨酸', '天冬氨酸', '牛磺酸']:
+        m = re.search(rf'{item}[^估]*?(\d+)', text)
+        if m:
+            metabolism.setdefault('氨基酸', {})[item] = int(m.group(1))
+    # 神经递质
+    for item in ['5-羟色胺', 'γ-氨基丁酸', '多巴胺', '乙酰胆碱', '组胺', '去甲肾上腺素']:
+        m = re.search(rf'{item}.*?(\d+)', text)
+        if m:
+            metabolism.setdefault('神经递质', {})[item] = int(m.group(1))
+    # 其他单项
+    for pattern, key in [
+        (r'嘌呤代谢.*?(\d+)', '嘌呤代谢'),
+        (r'谷胱甘肽.*?(\d+)', '三肽(谷胱甘肽)'),
+        (r'胆汁酸.*?(\d+)', '胆汁酸代谢'),
+        (r'硫辛酸.*?(\d+)', '抗自由基(硫辛酸)'),
+        (r'辅酶Q.*?(\d+)', '抗自由基(辅酶Q)'),
+    ]:
+        m = re.search(pattern, text)
+        if m:
+            metabolism[key] = int(m.group(1))
+    return metabolism
+
+
+def _parse_bj_antibiotics(text):
+    """提取抗生素风险评估"""
+    ab = {}
+    for cat in ANTIBIOTIC_CATEGORIES_BJ:
+        m = re.search(rf'{cat}[::\s]*(\d+)', text)
+        if m:
+            ab[cat] = int(m.group(1))
+    return ab
+
+
+def _parse_bj_toxins(text):
+    """提取毒性物质清除能力评估"""
+    toxins = {}
+    toxin_items = [
+        "苯甲酸酯", "对氨基苯甲酸乙酯", "对氟苯甲酸乙酯",
+        "氯烷烃和氯烯烃", "氯代环己烷", "氯苯",
+        "甲苯", "二甲苯", "硝基甲苯", "乙苯", "苯乙烯",
+        "阿特拉津", "己内酰胺", "双酚", "二恶英",
+        "萘", "多环芳烃",
+    ]
+    for item in toxin_items:
+        m = re.search(rf'{item}.*?(\d+)', text)
+        if m:
+            toxins[item] = int(m.group(1))
+    return toxins
+
+
+def _parse_bj_pathogens(text):
+    """提取胃肠道感染病原体评估"""
+    pathogens = []
+    for p in PATHOGEN_LIST_BJ:
+        idx = text.find(p)
+        if idx == -1: continue
+        chunk = text[idx:idx + 150]
+        val_m = re.search(r'(\d+\.?\d*)', chunk)
+        status_m = re.search(r'(检出|超标|未检出|正常)', chunk)
+        if val_m:
+            entry = {'名称': p, '检测值': float(val_m.group(1)) if '.' in val_m.group(1) else int(val_m.group(1))}
+            if status_m: entry['状态'] = status_m.group(1)
+            pathogens.append(entry)
+    return pathogens
+
+
+def _parse_bj_psych_eval(text, find_table_val=None):
+    """提取趣味肠菌评估"""
+    psych = {}
+    m = re.search(r'最高概率[::\s]*(\S+)', text)
+    if m: psych['人格特征'] = {'最高概率': m.group(1)}
+    # 认知功能(从表格)
+    if find_table_val:
+        cog = find_table_val('认知能力', val_col=1)
+        if cog:
+            psych['认知功能'] = {'认知能力评分': int(cog)}
+    return psych
+
+
+def _parse_bj_scfa_from_tables(find_table_rows):
+    """从表格提取短链脂肪酸合成能力"""
+    scfa = {}
+    for acid in ['甲酸', '乙酸', '丙酸', '丁酸', '戊酸', '己酸']:
+        rows = find_table_rows(acid)
+        for name, val in rows:
+            if acid in name:
+                scfa[acid] = int(val)
+                break
+    return scfa
+
+
+def _parse_bj_core_bacteria_from_tables(all_tables):
+    """从表格提取核心菌属精准分布"""
+    bacteria = []
+    for cn_name, lat_name in CORE_GENERA_BJ:
+        for table in all_tables:
+            for row in table:
+                row_str = ' '.join(str(c) for c in row if c)
+                if lat_name in row_str or cn_name in row_str:
+                    vals = [str(c).strip() for c in row if c and str(c).strip()]
+                    entry = {'拉丁名': lat_name, '中文名': cn_name}
+                    for v in vals:
+                        v_clean = v.replace('"', '').replace('#', '').strip()
+                        # 判断是否为范围值(如 0.0041-0.0339)
+                        if '-' in v_clean and v_clean.replace('.','').replace('-',' ').replace(' ','').isdigit():
+                            entry['参考范围'] = v_clean
+                        elif v_clean == 'ND':
+                            if '检测结果' not in entry:
+                                entry['检测结果'] = 0.0
+                        elif v_clean.replace('.','').replace('-','').isdigit() and v_clean != '':
+                            val = float(v_clean)
+                            if '检测结果' not in entry:
+                                entry['检测结果'] = val
+                            elif '人群百分位' not in entry:
+                                entry['人群百分位'] = val
+                    if '检测结果' in entry:
+                        bacteria.append(entry)
+                    break
+            if bacteria and bacteria[-1].get('拉丁名') == lat_name:
+                break
+    return bacteria
+
+
+def _parse_bj_nutrient_from_tables(find_table_rows, find_table_val):
+    """从表格提取营养物质及营养素代谢评估"""
+    metabolism = {}
+    # 主要营养物质
+    for n in ['碳水化合物', '蛋白质', '脂肪', '矿物质']:
+        rows = find_table_rows(n)
+        if rows:
+            for name, val in rows:
+                if n in name:
+                    metabolism.setdefault('主要营养物质代谢', {})[n] = int(val)
+    # 糖类
+    sugar_items = ['葡萄糖(糖酵解途径)', '葡萄糖(磷酸戊糖途径)', '果糖和甘露糖',
+                   '半乳糖', '淀粉和蔗糖', '氨基糖和核苷酸糖', '丙酮酸']
+    for item in sugar_items:
+        rows = find_table_rows(item[:3])
+        if rows:
+            for name, val in rows:
+                metabolism.setdefault('糖类代谢', {})[item] = int(val)
+    # 脂类
+    for item in ['甘油酯', '甘油磷脂', '甘油三酯', '鞘脂类', '脂肪酸',
+                 '硬脂酸', '棕榈酸', '花生四烯酸', '二十二碳六烯酸',
+                 'Omega-3', 'Omega-6']:
+        rows = find_table_rows(item[:3])
+        if rows:
+            for name, val in rows:
+                metabolism.setdefault('脂类代谢', {})[item] = int(val)
+    # 维生素
+    for item in ['维生素A', '维生素B1', '维生素B2', '维生素B3', '维生素B5',
+                 '维生素B6', '维生素B7', '维生素B12', '维生素C', '维生素D',
+                 '维生素E', '维生素K1', '维生素K2', '维生素K3', '叶酸']:
+        rows = find_table_rows(item)
+        if rows:
+            for name, val in rows:
+                metabolism.setdefault('维生素', {})[item] = int(val)
+    # 微量元素
+    for item in ['铁', '锌', '钙', '镁', '硒', '锰', '铜', '钴', '镍', '钼', '铬', '钒']:
+        rows = find_table_rows(item)
+        if rows:
+            for name, val in rows:
+                if name == item:
+                    metabolism.setdefault('微量元素', {})[item] = int(val)
+    # 氨基酸
+    for item in ['赖氨酸', '丝氨酸', '亮氨酸', '色氨酸', '苯丙氨酸',
+                 '缬氨酸', '组氨酸', '半胱氨酸', '酪氨酸', '丙氨酸',
+                 '脯氨酸', '苏氨酸', '谷氨酸', '异亮氨酸', '精氨酸',
+                 '蛋氨酸', '甘氨酸', '天冬氨酸', '牛磺酸']:
+        rows = find_table_rows(item[:2])
+        if rows:
+            for name, val in rows:
+                metabolism.setdefault('氨基酸', {})[item] = int(val)
+    # 神经递质
+    for item in ['5-羟色胺', 'γ-氨基丁酸', '多巴胺', '乙酰胆碱', '组胺', '去甲肾上腺素']:
+        rows = find_table_rows(item[:3])
+        if rows:
+            for name, val in rows:
+                metabolism.setdefault('神经递质', {})[item] = int(val)
+    # 其他单项
+    for item, key in [('嘌呤代谢', '嘌呤代谢'), ('谷胱甘肽', '三肽(谷胱甘肽)'),
+                       ('胆汁酸', '胆汁酸代谢'), ('硫辛酸', '抗自由基(硫辛酸)'),
+                       ('辅酶Q', '抗自由基(辅酶Q)')]:
+        v = find_table_val(item)
+        if v: metabolism[key] = int(v)
+    return metabolism
+
+
+def _parse_bj_antibiotics_from_tables(find_table_rows):
+    """从表格提取抗生素风险评估"""
+    ab = {}
+    for cat in ANTIBIOTIC_CATEGORIES_BJ:
+        rows = find_table_rows(cat, val_col=2)
+        for name, val in rows:
+            ab[cat] = int(val)
+    return ab
+
+
+def _parse_bj_toxins_from_tables(all_tables, find_table_rows):
+    """从表格提取毒性物质清除能力评估"""
+    toxins = {}
+    toxin_items = [
+        "苯甲酸酯", "对氨基苯甲酸乙酯", "对氟苯甲酸乙酯",
+        "氯烷烃和氯烯烃", "氯代环己烷", "氯苯",
+        "甲苯", "二甲苯", "硝基甲苯", "乙苯", "苯乙烯",
+        "阿特拉津", "己内酰胺", "双酚", "二恶英",
+        "萘", "多环芳烃",
+    ]
+    for item in toxin_items:
+        rows = find_table_rows(item[:3], name_col=1, val_col=2)
+        for name, val in rows:
+            toxins[item] = int(val)
+    return toxins
+
+
+def _parse_bj_overview(text):
+    """提取北京报告概述(统一到标准报告 overview 结构)"""
+    r = {}
+    m = re.search(r'检测编号[::\s]*(\S+)', text)
+    if m: r['report_number'] = m.group(1)
+    m = re.search(r'姓\s*名[::\s]*(\S+)', text)
+    if m: r['person_name'] = m.group(1)
+    m = re.search(r'年\s*龄[::\s]*(\S+)', text)
+    if m: r['age'] = m.group(1)
+    m = re.search(r'性\s*别[::\s]*(\S+)', text)
+    if m: r['gender'] = 'male' if m.group(1) in ('男', 'M') else 'female'
+    # V-02 fix: 补 report_date 提取;无则保持 null(不造假值)
+    report_date = _extract_report_date(text)
+    if report_date:
+        r['report_date'] = report_date
+    # 肠型
+    gut_type = _parse_bj_gut_type(text)
+    if gut_type: r['gut_type'] = gut_type
+    # GMHI → 健康总分
+    m = re.search(r'肠道微生物健康指数[::\s]*(\d+)', text)
+    if m: r['overallScore'] = int(m.group(1))
+    return r
+
+
+def _parse_beijing_report(file_path: str) -> dict:
+    """解析北京菌群报告 PDF,输出统一结构(pdfplumber 表格+文本混合提取)"""
+    try:
+        import pdfplumber
+        with pdfplumber.open(file_path) as pdf:
+            text = '\n'.join(page.extract_text() or '' for page in pdf.pages)
+            # 提取所有表格
+            all_tables = []
+            for page in pdf.pages:
+                tables = page.extract_tables()
+                for table in tables:
+                    if table and len(table) >= 2:
+                        all_tables.append(table)
+    except Exception as e:
+        from PyPDF2 import PdfReader
+        reader = PdfReader(file_path)
+        text = '\n'.join((page.extract_text() or '') for page in reader.pages)
+        all_tables = []
+
+    def find_table_rows(keyword, val_col=1, name_col=0, try_all=False):
+        """从表格中找指定关键词的数据行"""
+        rows = []
+        for table in all_tables:
+            for row in table:
+                row_str = ' '.join(str(c) for c in row if c)
+                if keyword in row_str:
+                    if name_col < len(row) and val_col < len(row):
+                        name = str(row[name_col] or '').strip()
+                        val = str(row[val_col] or '').strip()
+                        if name and val and val.replace('.','').replace('-','').isdigit():
+                            rows.append((name, val))
+            if rows and not try_all:
+                break
+        return rows
+
+    def find_table_val(keyword, val_col=1, name_col=0):
+        """从表格中找单个值"""
+        for table in all_tables:
+            for row in table:
+                row_str = ' '.join(str(c) for c in row if c)
+                if keyword in row_str:
+                    if val_col < len(row):
+                        val = str(row[val_col] or '').strip()
+                        if val and val.replace('.','').isdigit():
+                            return val
+        return None
+
+    result = {
+        'format': 'beijing',
+        'overview': _parse_bj_overview(text),
+        'disease_risks': [],
+        'nutrition': [],
+        'amino_acids': [],
+        'vitamins': [],
+        'trace_elements': [],
+        '菌群检出详细列表': {},
+        '个体化食物推荐表': {'格式': 'not_found', '条目数': 0, '数据': []},
+        # 北京报告特有指标
+        '肠道微生物健康指数': _parse_bj_gmhi(text),
+        '菌群多样性': _parse_bj_diversity(text),
+        '肠道黏膜屏障': _parse_bj_barrier(text),
+        '菌群表型评估': _parse_bj_phenotype(text),
+        '短链脂肪酸合成能力': _parse_bj_scfa_from_tables(find_table_rows),
+        '肠道菌群精准分布': _parse_bj_core_bacteria_from_tables(all_tables),
+        '营养物质及营养素代谢评估': _parse_bj_nutrient_from_tables(find_table_rows, find_table_val),
+        '抗生素风险评估': _parse_bj_antibiotics_from_tables(find_table_rows),
+        '毒性物质清除能力评估': _parse_bj_toxins_from_tables(all_tables, find_table_rows),
+        '趣味肠菌评估': _parse_bj_psych_eval(text, find_table_val),
+        '胃肠道感染病原体': [],
+        '健康整体评估': {},
+        '肠道菌群主要检测结果': {},
+    }
+
+    # 从表格更新 GMHI/抗炎/免疫/纤维/多样性/屏障
+    gmhi_val = find_table_val('肠道微生物健康指数', val_col=1)
+    if gmhi_val:
+        result['肠道微生物健康指数']['肠道微生物健康指数'] = float(gmhi_val)
+        score = float(gmhi_val)
+        if score >= 90: result['肠道微生物健康指数']['健康状态'] = '健康'
+        elif score >= 80: result['肠道微生物健康指数']['健康状态'] = '健康倾向'
+        elif score >= 40: result['肠道微生物健康指数']['健康状态'] = '亚健康'
+        elif score >= 20: result['肠道微生物健康指数']['健康状态'] = '不健康倾向'
+        else: result['肠道微生物健康指数']['健康状态'] = '不健康'
+    for attr, kw in [('肠道抗炎能力', '抗炎能力'), ('肠道免疫力', '免疫力'),
+                     ('肠道膳食纤维需求', '膳食纤维需求')]:
+        v = find_table_val(kw)
+        if v:
+            result.setdefault('肠道菌群主要检测结果', {})[attr] = int(v)
+            if '抗炎' in kw: result['overview']['inflammationScore'] = int(v)
+            elif '免疫' in kw: result['overview']['immunityScore'] = int(v)
+    # 多样性
+    div_val = find_table_val('肠道微生物多样性', val_col=1)
+    if div_val:
+        result['菌群多样性']['Shannon指数'] = float(div_val)
+    # BE比值
+    be_val = find_table_val('B/E比值', val_col=1)
+    if be_val:
+        result['肠道黏膜屏障']['BE比值'] = float(be_val)
+    bi_val = find_table_val('双歧杆菌属', val_col=1)
+    if bi_val:
+        result['肠道黏膜屏障']['双歧杆菌属'] = float(bi_val)
+    ent_val = find_table_val('肠杆菌科', val_col=1)
+    if ent_val:
+        result['肠道黏膜屏障']['肠杆菌科'] = float(ent_val)
+    # 肠型
+    gut_type = _parse_bj_gut_type(text)
+    balance = _parse_bj_balance(text)
+    if gut_type or balance:
+        result['健康整体评估'] = {}
+        if gut_type: result['健康整体评估']['肠型'] = gut_type
+        if balance: result['健康整体评估']['菌群平衡评估'] = balance
+
+    # 疾病风险评估(文本提取)
+    disease_risks = _parse_bj_disease_risks(text)
+    if disease_risks:
+        result['disease_risks'] = disease_risks
+
+    # 病原体
+    pathogens = _parse_bj_pathogens(text)
+    if pathogens:
+        result['胃肠道感染病原体'] = pathogens
+
+    # 肠道菌群状态 → overview.gutStatusLevel(P1)
+    status = result.get('肠道微生物健康指数', {}).get('肠道菌群状态')
+    if status:
+        result['overview']['gutStatusLevel'] = status
+
+    # 营养物质 → 标准字段映射
+    metabolism = result.get('营养物质及营养素代谢评估', {})
+    if metabolism.get('主要营养物质代谢'):
+        result['nutrition'] = [
+            {'name': k, 'value': str(v), 'status': '正常' if v >= 60 else '偏低'}
+            for k, v in metabolism['主要营养物质代谢'].items()
+        ]
+    if metabolism.get('氨基酸'):
+        result['amino_acids'] = [
+            {'name': k, 'value': str(v), 'status': '正常' if v >= 60 else '偏低'}
+            for k, v in metabolism['氨基酸'].items()
+        ]
+    if metabolism.get('维生素'):
+        result['vitamins'] = [
+            {'name': k, 'value': str(v), 'status': '正常' if v >= 60 else '偏低'}
+            for k, v in metabolism['维生素'].items()
+        ]
+    if metabolism.get('微量元素'):
+        result['trace_elements'] = [
+            {'name': k, 'value': str(v), 'status': '正常' if v >= 60 else '偏低'}
+            for k, v in metabolism['微量元素'].items()
+        ]
+
+    return result

+ 110 - 0
cfc-langgraph/app/portrait_service.py

@@ -0,0 +1,110 @@
+"""用户画像 prompt 组装服务
+
+职责:
+1. 拉取用户自定义画像文本(600s 缓存)
+2. 拉取 profile_snapshot 并渲染为文本(900s 缓存)
+3. 拼装成 SystemMessage 内容;无数据时返回 None
+"""
+import time
+import logging
+from app.tools.java_client import JavaClient
+
+logger = logging.getLogger(__name__)
+
+_TTL_PROMPT = 600    # 用户自定义 prompt 缓存 10 分钟
+_TTL_SNAPSHOT = 900  # 画像快照缓存 15 分钟
+
+_cache_prompt: dict = {}
+_cache_snapshot: dict = {}
+
+
+def _render_snapshot(profile: dict) -> str:
+    """将 profile Map 渲染为中文指标清单文本"""
+    if not profile or "error" in profile:
+        return ""
+    lines = []
+    member = profile.get("member") or {}
+    name = member.get("name", "用户")
+    age = member.get("age", "?")
+    gender_raw = str(member.get("gender", ""))
+    gender = "男" if gender_raw == "male" else "女" if gender_raw == "female" else "未知"
+    lines.append(f"## 画像对象:{name}({age}岁,{gender})")
+
+    dims = profile.get("dimension_scores") or {}
+    if dims:
+        lines.append(f"五维评分:身 {dims.get('body', '?')} 智 {dims.get('wisdom', '?')} "
+                     f"心 {dims.get('mind', '?')} 行 {dims.get('action', '?')} 富 {dims.get('wealth', '?')}")
+
+    body = profile.get("body_metrics") or {}
+    if body.get("sleep_dur_avg"):
+        lines.append(f"平均睡眠:{body['sleep_dur_avg']}小时/天")
+    if body.get("exercise_count_week"):
+        lines.append(f"周运动频次:{body['exercise_count_week']}次")
+
+    mind = profile.get("mind_metrics") or {}
+    if mind.get("stress_avg"):
+        lines.append(f"平均压力:{mind['stress_avg']}/10")
+
+    problems = profile.get("problem_domains") or []
+    if problems:
+        lines.append(f"关注问题域:{', '.join(problems[:5])}")
+
+    return "\n".join(lines)
+
+
+async def get_user_portrait_text(java: JavaClient, user_id: int, member_id) -> str | None:
+    """返回画像 SystemMessage 内容;无画像数据时返回 None"""
+    parts = []
+
+    # 1. 用户自定义 prompt(600s 缓存)
+    now = time.time()
+    cached_text, cached_ts = _cache_prompt.get(user_id, (None, 0))
+    if now - cached_ts < _TTL_PROMPT and cached_text is not None:
+        user_text = cached_text
+    else:
+        try:
+            client = await java._get_client()
+            resp = await client.post("/api/user/portrait/get", json={"userId": user_id}, timeout=5.0)
+            data = resp.json()
+            user_text = (data.get("data") or {}).get("portraitPrompt") or ""
+            _cache_prompt[user_id] = (user_text, now)
+        except Exception as e:
+            logger.warning("拉取用户画像 prompt 失败: %s", e)
+            user_text = ""
+
+    if user_text.strip():
+        parts.append(user_text)
+
+    # 2. 快照渲染文本(仅当有 member_id 时)
+    if member_id:
+        snap_now = time.time()
+        cached_snap, cached_snap_ts = _cache_snapshot.get(int(member_id), (None, 0))
+        if snap_now - cached_snap_ts < _TTL_SNAPSHOT and cached_snap is not None:
+            snap_text = cached_snap
+        else:
+            try:
+                profile = await java.get_member_profile(int(member_id))
+                snap_text = _render_snapshot(profile) if profile else ""
+                _cache_snapshot[int(member_id)] = (snap_text, snap_now)
+            except Exception as e:
+                logger.warning("拉取成员画像快照失败: %s", e)
+                snap_text = ""
+
+        if snap_text.strip():
+            if user_text.strip():
+                parts.append("\n---参考指标---\n" + snap_text)
+            else:
+                parts.append("以下是用户画像数据(系统自动生成),请结合这些数据给出更针对性的建议:\n" + snap_text)
+
+    return "\n\n".join(parts) if parts else None
+
+
+def clear_cache(user_id: int | None = None, member_id: int | None = None):
+    """清除缓存"""
+    if user_id is not None:
+        _cache_prompt.pop(user_id, None)
+    if member_id is not None:
+        _cache_snapshot.pop(member_id, None)
+    if user_id is None and member_id is None:
+        _cache_prompt.clear()
+        _cache_snapshot.clear()

+ 130 - 0
cfc-langgraph/app/prompt_service.py

@@ -0,0 +1,130 @@
+"""系统提示词动态加载服务
+
+从 cfc-web 管理的 system_prompts 表(Java /api/system-prompts/get)加载提示词,
+带进程内缓存 + 超时降级到内置默认值。
+"""
+import time
+import logging
+from app.tools.java_client import JavaClient
+
+logger = logging.getLogger(__name__)
+
+_cache: dict[str, str] = {}
+_cache_ts: dict[str, float] = {}
+_TTL_SECONDS = 300
+
+DEFAULT_PROMPTS: dict[str, str] = {
+    "health_butler": """你是一个家庭AI健康管家, 为用户提供专业、温暖的个性化健康建议。
+你的能力:
+1. 基于健康知识库(菌属功能、指标解读、营养素、食物)提供科学建议
+2. 解读健康报告数据, 结合知识库给出改善方案
+3. 根据菌群检测结果推荐精准营养方案
+4. 提供可执行的健康微行动
+回答原则:
+1. 用中文, 像家庭医生一样亲切但专业
+2. 引用知识库中的菌属/指标/食物信息作为证据
+3. 优先使用知识库数据, 其次使用通用健康知识
+4. 需要产品推荐时使用搜索工具
+5. 生成 [TASK: {"title": "任务名", "dimension": "身", "points": 10, "frequency": "每天"}] 标记创建健康行动任务
+6. 超出知识库范围的慢性病/急症问题, 建议咨询专业医生
+7. 不要编造医学建议, 不夸大效果""",
+    "health_coach": """你是一个儿童健康教练,喜欢用提问的方式引导家长发现问题和解决方案。
+核心原则:
+1. 先问后答:不要直接给答案,用问题引导家长思考
+2. 用开放式问题了解情况,再给针对性建议
+3. 语气温暖,像一个耐心的教练在陪伴家长成长
+你的职责:
+1. 儿童体质调理(如挑食、瘦弱、易疲劳、反复生病)—— 用提问了解情况
+2. 科学喂养和营养建议 —— 先问饮食现状再给建议
+3. 日常保健(睡眠、运动、季节防护)—— 引导家长发现生活中的问题
+4. 体质辨识基础咨询 —— 通过提问帮助家长理解孩子体质特点
+5. 健康问题判断 —— 先收集症状信息再建议是否就医
+回答结构: 提问-分析-建议-跟进""",
+    "chat_assistant": """你是一个儿童成长家庭助手, 回答关于孩子成长、健康、教育的各种问题。
+
+你可以使用搜索工具查找商品、活动和文章来辅助回答。
+
+回答原则:
+1. 用中文, 语气温暖亲切
+2. 如果用户提到具体孩子, 参考提供的家庭上下文
+3. 需要推荐时使用搜索工具
+4. 可以生成 [TASK: {"title": "任务名", "dimension": "身/心/智/行/富", "points": 10}] 标记来创建行动任务
+5. 不要编造医疗建议, 严重问题建议咨询医生""",
+    "analysis": """你是一个儿童健康报告解读专家。根据健康报告数据和调研问卷, 提供专业、易懂的分析。
+
+分析原则:
+1. 用通俗语言解释各项指标含义
+2. 关注异常指标, 给出改善建议
+3. 结合问卷数据提供个性化分析
+4. 五维能量(身/心/智/行/富)角度解读整体状况
+5. 输出格式: 总体评估 → 分项分析 → 改善建议
+""",
+    "recommend": """你是一个儿童成长营养推荐助手。根据用户的需求和营养标签, 推荐合适的商品、活动或文章。
+
+推荐原则:
+1. 首先尝试使用搜索工具查找匹配的内容
+2. 如果搜索结果为空, 基于你的知识给出建议
+3. 每项推荐必须附带推荐理由
+4. 以 JSON 格式输出推荐结果
+
+输出格式:
+{
+    "items": [
+        {
+            "source": "tool" 或 "knowledge",
+            "type": "product" / "activity" / "article",
+            "id": 数字,
+            "name": "名称",
+            "description": "描述",
+            "reason": "为什么推荐这个"
+        }
+    ]
+}
+""",
+    "article_quiz": """你是一位家庭教育出题助手。根据给定的文章内容,为读者生成 3 道单项选择题。
+
+要求:
+1. 每题 4 个选项,选项以 "A. "、"B. "、"C. "、"D. " 开头
+2. 题目考察文章核心内容的理解,适合青少年读者
+3. 每题标注所属五维(body/mind/wisdom/action/wealth),缺省为 wisdom
+4. 以 JSON 数组格式返回,不要返回其他文字,只返回 JSON 数组
+
+输出格式:
+[
+  {"question": "问题", "options": ["A. xxx", "B. xxx", "C. xxx", "D. xxx"], "answer": "A", "dimension": "wisdom", "explanation": "解析"}
+]
+""",
+}
+
+
+async def get_prompt(prompt_key: str) -> str:
+    """获取指定提示词,带缓存与降级。返回 str 内容(找不到/禁用返回空串)。"""
+    now = time.time()
+    if prompt_key in _cache and now - _cache_ts.get(prompt_key, 0) < _TTL_SECONDS:
+        return _cache[prompt_key]
+
+    try:
+        java = JavaClient()
+        client = await java._get_client()
+        resp = await client.post("/api/system-prompts/get", json={"promptKey": prompt_key}, timeout=5.0)
+        data = resp.json()
+        if data.get("code") == 200 and data.get("data"):
+            content = data["data"].get("content")
+            if content:
+                _cache[prompt_key] = content
+                _cache_ts[prompt_key] = now
+                return content
+    except Exception as e:
+        logger.warning("加载提示词 %s 失败: %s", prompt_key, e)
+
+    return DEFAULT_PROMPTS.get(prompt_key, "")
+
+
+def clear_cache(prompt_key: str | None = None):
+    """清除缓存(管理端修改后调用)"""
+    if prompt_key:
+        _cache.pop(prompt_key, None)
+        _cache_ts.pop(prompt_key, None)
+    else:
+        _cache.clear()
+        _cache_ts.clear()

+ 2 - 0
cfc-langgraph/app/rag/__init__.py

@@ -0,0 +1,2 @@
+from .embeddings import get_embeddings
+from .retriever import RagRetriever

+ 71 - 0
cfc-langgraph/app/rag/embeddings.py

@@ -0,0 +1,71 @@
+from typing import List
+import time
+import logging
+from langchain_core.embeddings import Embeddings
+from openai import OpenAI, RateLimitError
+from app.config import settings
+
+logger = logging.getLogger(__name__)
+
+
+class SiliconFlowEmbeddings(Embeddings):
+    """OpenAI 兼容 embeddings 直连客户端(绕开 langchain tiktoken token 化)
+
+    langchain 的 OpenAIEmbeddings 默认 tiktoken_enabled=True,会把文本编码成
+    整数 token 数组发送给 API(OpenAI 官方接受,但 siliconflow 等第三方网关
+    只接受字符串 input,导致 400 code:20015 parameter invalid)。
+    本类直接用 openai SDK 发送字符串数组,兼容 siliconflow 等网关。
+
+    内置 429 TPM 指数退避重试:SiliconFlow 全量同步易触 TPM 限额,429 是
+    临时性状态,退避重试能自动恢复完成,避免 sync 整段中断。
+    """
+
+    _BATCH_SIZE = 32
+    _THROTTLE_SECONDS = 0.02
+    _MAX_RETRY = 3
+    _INITIAL_RETRY_SECONDS = 2.0
+
+    def __init__(self, model: str, api_key: str, base_url: str):
+        self.model = model
+        self.client = OpenAI(api_key=api_key, base_url=base_url)
+
+    def _call_with_retry(self, batch):
+        wait = self._INITIAL_RETRY_SECONDS
+        for attempt in range(self._MAX_RETRY + 1):
+            try:
+                return self.client.embeddings.create(model=self.model, input=batch)
+            except RateLimitError as e:
+                if attempt == self._MAX_RETRY:
+                    raise
+                logger.warning("embeddings 429 TPM 限制,%.0fs 后重试 (%d/%d)", wait, attempt + 1, self._MAX_RETRY)
+                time.sleep(wait)
+                wait = min(wait * 2, 30.0)
+        raise RuntimeError("unreachable")
+
+    def embed_documents(self, texts: List[str]) -> List[List[float]]:
+        result = []
+        for i in range(0, len(texts), self._BATCH_SIZE):
+            batch = texts[i:i + self._BATCH_SIZE]
+            resp = self._call_with_retry(batch)
+            result.extend(d.embedding for d in resp.data)
+            if i + self._BATCH_SIZE < len(texts):
+                time.sleep(self._THROTTLE_SECONDS)
+        return result
+
+    def embed_query(self, text: str) -> List[float]:
+        resp = self._call_with_retry([text])
+        return resp.data[0].embedding
+
+
+_embeddings = None
+
+
+def get_embeddings():
+    global _embeddings
+    if _embeddings is None:
+        _embeddings = SiliconFlowEmbeddings(
+            model=settings.embedding_model,
+            api_key=settings.effective_embedding_api_key,
+            base_url=settings.effective_embedding_base_url,
+        )
+    return _embeddings

+ 53 - 0
cfc-langgraph/app/rag/loader.py

@@ -0,0 +1,53 @@
+from app.tools.java_client import JavaClient
+from typing import Optional
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class KnowledgeLoader:
+    """知识库加载器: 从 Java 侧拉取文章并格式化"""
+
+    def __init__(self):
+        self.java = JavaClient()
+
+    async def load_all_articles(self) -> list[dict]:
+        """获取所有已发布文章"""
+        return await self.java.get_published_articles()
+
+    async def load_updated_since(self, since: str) -> list[dict]:
+        """增量获取: 获取某个时间后更新的文章"""
+        try:
+            client = await self.java._get_client()
+            resp = await client.post("/api/article/updated-since", json={
+                "since": since,
+                "status": "published",
+            })
+            data = resp.json()
+            if data.get("code") == 200:
+                body = data.get("data", [])
+                # 兼容两种响应:直接 list 或 {records:[...]} 分页结构
+                if isinstance(body, dict):
+                    body = body.get("records", []) or []
+                return body
+        except Exception as e:
+            logger.warning("增量获取文章失败: %s", e)
+        return []
+
+    def format_for_indexing(self, articles: list[dict]) -> list[dict]:
+        """将文章格式化为可索引的文档"""
+        docs = []
+        for article in articles:
+            content = f"{article.get('title', '')}\n\n{article.get('summary', '')}\n\n{article.get('content', '')}"
+            docs.append({
+                "id": f"article_{article['id']}",
+                "content": content,
+                "metadata": {
+                    "source": "article",
+                    "article_id": article["id"],
+                    "title": article.get("title", ""),
+                    "tags": article.get("tags", ""),
+                    "updated_at": article.get("updatedAt", ""),
+                },
+            })
+        return docs

+ 129 - 0
cfc-langgraph/app/rag/microbiome_loader.py

@@ -0,0 +1,129 @@
+"""菌群知识库加载器: 从 Java 后端同步文章到 ChromaDB"""
+import logging
+import httpx
+from langchain_chroma import Chroma
+from langchain_core.documents import Document
+from app.config import settings
+from app.rag.embeddings import get_embeddings
+from app.rag.splitter import get_knowledge_splitter
+
+logger = logging.getLogger(__name__)
+COLLECTION_NAME = "microbiome_kb"
+
+
+class MicrobiomeLoader:
+
+    def __init__(self):
+        self.embeddings = get_embeddings()
+        self.vectorstore = Chroma(
+            collection_name=COLLECTION_NAME,
+            embedding_function=self.embeddings,
+            persist_directory=settings.chroma_db_path,
+        )
+        self.splitter = get_knowledge_splitter()
+
+    async def fetch_articles(self, keyword=None) -> list[dict]:
+        client = httpx.AsyncClient(base_url=settings.java_base_url, timeout=120)
+        try:
+            if keyword:
+                resp = await client.post("/api/microbiome/article/search", json={"keyword": keyword})
+                data = resp.json()
+                if data.get("code") == 200:
+                    return data.get("data", [])
+            else:
+                page = 1
+                size = 50
+                records = []
+                while True:
+                    resp = await client.post("/api/microbiome/article/list",
+                                             json={"page": page, "size": size, "keyword": "", "category": ""})
+                    data = resp.json()
+                    if data.get("code") != 200:
+                        break
+                    body = data.get("data", {}) or {}
+                    items = body.get("records", []) or []
+                    records.extend(items)
+                    total = body.get("total", 0)
+                    if page * size >= int(total or 0) or not items:
+                        break
+                    page += 1
+                return records
+        except Exception as e:
+            logger.warning("获取菌群文章失败: %s", e)
+        finally:
+            await client.aclose()
+        return []
+
+    async def fetch_article(self, article_id: int) -> dict | None:
+        client = httpx.AsyncClient(base_url=settings.java_base_url, timeout=120)
+        try:
+            resp = await client.post("/api/microbiome/article/detail", json={"id": article_id})
+            data = resp.json()
+            if data.get("code") == 200:
+                return data.get("data")
+        except Exception as e:
+            logger.warning("获取菌群文章详情失败: %s", e)
+        finally:
+            await client.aclose()
+        return None
+
+    def _build_chunks(self, article: dict) -> list[Document]:
+        content = f"{article.get('title', '')}\n\n{article.get('content', '')}"
+        split_texts = self.splitter.split_text(content)
+        category = article.get("category", "科普")
+        tags = article.get("tags", "")
+        docs = []
+        for i, text in enumerate(split_texts):
+            docs.append(Document(
+                page_content=text,
+                metadata={
+                    "id": f"article_{article['id']}_{i}",
+                    "postId": str(article["id"]),
+                    "title": article.get("title", ""),
+                    "category": category,
+                    "tags": tags,
+                    "source_url": article.get("sourceUrl", ""),
+                    "pub_date": article.get("pubDate", ""),
+                    "chunk_index": i,
+                    "chunk_total": len(split_texts),
+                    "source": "microbiome_kb",
+                },
+            ))
+        return docs
+
+    async def sync_all(self):
+        articles = await self.fetch_articles()
+        if not articles:
+            logger.info("菌群知识库同步: 无文章")
+            return
+        try:
+            existing_ids = self.vectorstore.get()["ids"]
+            if existing_ids:
+                self.vectorstore.delete(existing_ids)
+        except Exception:
+            pass
+        all_docs = []
+        for article in articles:
+            all_docs.extend(self._build_chunks(article))
+        for i in range(0, len(all_docs), 200):
+            await self.vectorstore.aadd_documents(all_docs[i:i + 200])
+        logger.info("菌群知识库全量同步完成: %d 篇文章, %d 个chunk", len(articles), len(all_docs))
+
+    async def sync_one(self, article_id: int):
+        article = await self.fetch_article(article_id)
+        if not article:
+            logger.warning("菌群文章不存在: %d", article_id)
+            return
+        prefix = f"article_{article_id}_"
+        try:
+            existing = self.vectorstore.get()
+            ids_to_delete = [i for i in existing["ids"] if i.startswith(prefix)]
+            if ids_to_delete:
+                self.vectorstore.delete(ids_to_delete)
+        except Exception:
+            pass
+        docs = self._build_chunks(article)
+        if docs:
+            await self.vectorstore.aadd_documents(docs)
+        logger.info("菌群文章同步完成: %d (%s), %d 个chunk",
+                    article_id, article.get("title", ""), len(docs))

+ 74 - 0
cfc-langgraph/app/rag/retriever.py

@@ -0,0 +1,74 @@
+from langchain_chroma import Chroma
+from langchain_openai import ChatOpenAI
+from app.config import settings
+from app.rag.embeddings import get_embeddings
+from app.tools.java_client import JavaClient
+from typing import Optional
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class RagRetriever:
+    """简单的向量检索器 - 基于 ChromaDB"""
+
+    def __init__(self, collection_name: str = "cfc_knowledge"):
+        embeddings = get_embeddings()
+        self.vectorstore = Chroma(
+            collection_name=collection_name,
+            embedding_function=embeddings,
+            persist_directory=settings.chroma_db_path,
+        )
+        self.java_client = JavaClient()
+
+    async def initialize(self):
+        """初始化向量库连接(不写入任何内容)。
+
+        内容统一由 app.tasks.knowledge_sync.sync_knowledge_base 维护(article/microbiome/dan_knowledge 三源)。
+
+        旧实现在此额外写入一版粗粒度文章索引(metadata.type=article,标题+摘要+标签),
+        与同步任务写入的 metadata.source=article 分块索引(标题+摘要+正文)构成同一批文章的
+        双份向量,且每次容器重启都会追加,导致 HNSW 索引无限膨胀。治理后统一移除。
+        """
+        try:
+            count = self.vectorstore._collection.count()
+            logger.info("知识库初始化完成:collection 当前 %d 个文档(内容同步由 knowledge_sync 维护)", count)
+        except Exception as e:
+            logger.warning("知识库初始化失败:%s", e)
+
+    async def retrieve(
+        self,
+        query: str,
+        filters: Optional[dict] = None,
+        k: int = 5,
+    ) -> list[dict]:
+        """向量相似度检索"""
+        results = []
+        
+        # 向量检索
+        filter_query = {"user_id": filters["user_id"]} if filters and "user_id" in filters else None
+        
+        docs = self.vectorstore.similarity_search(
+            query,
+            k=k * 2,  # 多取一些
+            filter=filter_query,
+        )
+        
+        # 格式化结果并去重
+        seen = set()
+        for doc in docs:
+            content_hash = hash(doc.page_content[:100])
+            if content_hash in seen:
+                continue
+            seen.add(content_hash)
+            
+            results.append({
+                "content": doc.page_content,
+                "metadata": doc.metadata,
+                "score": doc.metadata.get("score", 0) if hasattr(doc, "metadata") else 0,
+            })
+            
+            if len(results) >= k:
+                break
+        
+        return results[:k]

+ 21 - 0
cfc-langgraph/app/rag/splitter.py

@@ -0,0 +1,21 @@
+from langchain_text_splitters import RecursiveCharacterTextSplitter
+
+
+def get_knowledge_splitter():
+    """知识库文档分块器"""
+    return RecursiveCharacterTextSplitter(
+        chunk_size=500,
+        chunk_overlap=50,
+        separators=["\n\n", "\n", "。", "!", "?", ",", " ", ""],
+        length_function=len,
+    )
+
+
+def get_summary_splitter():
+    """摘要分块器 (用于对话记忆)"""
+    return RecursiveCharacterTextSplitter(
+        chunk_size=1000,
+        chunk_overlap=100,
+        separators=["\n\n", "\n", "。", " ", ""],
+        length_function=len,
+    )

+ 0 - 0
cfc-langgraph/app/tasks/__init__.py


+ 225 - 0
cfc-langgraph/app/tasks/knowledge_sync.py

@@ -0,0 +1,225 @@
+"""知识库同步定时任务: 三源(article/microbiome/dan_knowledge)幂等同步到 ChromaDB
+
+治理改造(2026-10-19):
+- article 由「只增量追加」改为「全量重建」:旧实现永不删除 article 旧块,
+  导致下架/删除文章残留在向量库、HNSW 索引无限膨胀(曾达 11.8GB)。
+- 三源 metadata 键统一(id/source/post_id/title/category/tags/dimensions/source_url/pub_date/chunk_index/chunk_total),
+  消除旧实现 retriever.initialize 的 metadata.type=article 与同步任务 metadata.source=article 双份数据。
+- 显式传入 Chroma doc id(source_itemId_chunkIdx),写入幂等,可安全重试。
+- 每源独立 try/except,一处失败不影响其他源。
+"""
+import asyncio
+import datetime
+import json
+import logging
+import os
+
+from langchain_chroma import Chroma
+from langchain_core.documents import Document
+
+from app.config import settings
+from app.rag.embeddings import get_embeddings
+from app.rag.loader import KnowledgeLoader
+from app.rag.splitter import get_knowledge_splitter
+
+logger = logging.getLogger(__name__)
+
+SYNC_STATE_FILE = os.path.join(settings.chroma_db_path, ".sync_state")
+BATCH_SIZE = 100          # 每批写入的块数
+MAX_WRITE_RETRY = 3       # 单批写入失败重试次数(配合 embedding 429 退避)
+
+
+def _load_sync_state() -> dict:
+    try:
+        if os.path.exists(SYNC_STATE_FILE):
+            with open(SYNC_STATE_FILE) as f:
+                return json.load(f)
+    except Exception:
+        pass
+    return {"last_sync": "2000-01-01T00:00:00"}
+
+
+def _save_sync_state(state: dict):
+    os.makedirs(os.path.dirname(SYNC_STATE_FILE), exist_ok=True)
+    with open(SYNC_STATE_FILE, "w") as f:
+        json.dump(state, f)
+
+
+def _delete_by_prefix(vectorstore, prefix: str):
+    """删除指定 source 的所有旧块。
+
+    修复: 原实现 vectorstore.get() 会拉取整个 collection (数百万条 embedding)
+    到内存, 导致 gunicorn worker OOM 反复重启。改为按 metadata where 过滤
+    只取目标 source 的 ids 再删除, 内存占用与数据总量无关。
+    """
+    try:
+        collection = vectorstore._collection
+        existing = collection.get(where={"source": prefix}, include=[])
+        ids = existing.get("ids", []) or []
+        if ids:
+            collection.delete(ids=ids)
+            logger.info("已删除 source=%s 的 %d 个旧块", prefix, len(ids))
+        else:
+            logger.info("无 source=%s 旧块可删除", prefix)
+    except Exception as e:
+        logger.warning("删除 source=%s 旧块失败: %s", prefix, e)
+
+
+def _build_chunks(splitter, items: list[dict], source: str) -> tuple[list[Document], list[str]]:
+    """将条目分块,返回 (chunks, doc_ids)。
+
+    doc_id 形如 source_itemId_chunkIdx,作为 Chroma 文档 ID 显式传入,
+    保证同一知识条目的块可被幂等覆盖(而非每次生成随机 UUID 无限累积)。
+    兼容旧 metadata 字段映射(sourceUrl/pubDate)。
+    """
+    chunks: list[Document] = []
+    ids: list[str] = []
+    seen_ids: set[str] = set()
+    unique_items: list[dict] = []
+    for item in items:
+        item_id = item.get("id")
+        if item_id is None:
+            continue
+        key = str(item_id)
+        if key in seen_ids:
+            continue  # 数据源重复 id(如 join 重复行),仅保留先出现者,避免 doc_id 幂等覆盖
+        seen_ids.add(key)
+        unique_items.append(item)
+    if len(unique_items) != len(items):
+        logger.warning("知识库同步[%s]: 数据源含 %d 条重复 id,去重后 %d 篇",
+                       source, len(items) - len(unique_items), len(unique_items))
+    for item in unique_items:
+        item_id = item.get("id")
+        title = item.get("title", "")
+        content = item.get("content", "")
+        if not content:
+            continue
+        # 若 content 已含 title 前缀则不重复拼接
+        full_text = f"{title}\n\n{content}" if title and title not in content else content
+        split_texts = splitter.split_text(full_text)
+        for i, text in enumerate(split_texts):
+            doc_id = f"{source}_{item_id}_{i}"
+            metadata = {
+                "id": doc_id,
+                "source": source,
+                "post_id": str(item_id),
+                "title": title,
+                "category": item.get("category", ""),
+                "tags": item.get("tags", ""),
+                "dimensions": item.get("dimensions", ""),
+                "source_url": item.get("source_url", "") or item.get("sourceUrl", ""),
+                "pub_date": item.get("pub_date", "") or item.get("pubDate", ""),
+                "chunk_index": i,
+                "chunk_total": len(split_texts),
+            }
+            chunks.append(Document(page_content=text, metadata=metadata))
+            ids.append(doc_id)
+    return chunks, ids
+
+
+async def _add_batch_with_retry(vectorstore, chunks: list, ids: list, label: str, start: int):
+    """单批写入,失败指数退避重试(embedding 网关限流时自动恢复)。"""
+    delay = 2.0
+    for attempt in range(MAX_WRITE_RETRY + 1):
+        try:
+            await vectorstore.aadd_documents(chunks, ids=ids)
+            return
+        except Exception as e:
+            if attempt == MAX_WRITE_RETRY:
+                raise
+            logger.warning("向量化写入失败[%s] %d-%d,%.0fs 后重试 (%d/%d): %s",
+                           label, start, start + len(chunks), delay, attempt + 1, MAX_WRITE_RETRY, e)
+            await asyncio.sleep(delay)
+            delay = min(delay * 2, 30.0)
+
+
+async def _write_chunks(vectorstore, chunks: list, ids: list, label: str):
+    """分批写入并输出进度日志。"""
+    total = len(chunks)
+    if total == 0:
+        logger.info("知识库同步[%s]: 无内容可写入", label)
+        return
+    for i in range(0, total, BATCH_SIZE):
+        batch_chunks = chunks[i:i + BATCH_SIZE]
+        batch_ids = ids[i:i + BATCH_SIZE]
+        await _add_batch_with_retry(vectorstore, batch_chunks, batch_ids, label, i)
+        done = min(i + BATCH_SIZE, total)
+        logger.info("向量化写入进度[%s]: %d/%d", label, done, total)
+
+
+async def _sync_source(vectorstore, splitter, source: str, fetch_func) -> int:
+    """全量重建一个 source:先删旧块,再全量拉取重建,返回写入块数。"""
+    try:
+        _delete_by_prefix(vectorstore, source)
+        items = await fetch_func()
+        chunks, ids = _build_chunks(splitter, items, source)
+        await _write_chunks(vectorstore, chunks, ids, source)
+        logger.info("知识库同步[%s]: %d 篇 -> %d 块", source, len(items), len(chunks))
+        return len(chunks)
+    except Exception as e:
+        logger.error("知识库同步[%s] 失败: %s", source, e)
+        return 0
+
+
+def _format_article_item(a: dict) -> dict:
+    """兼容 Java 文章结构,统一映射为题名/摘要/正文/标签/时间。"""
+    title = a.get("title", "")
+    return {
+        "id": a["id"],
+        "title": title,
+        "content": f"{a.get('summary', '')}\n\n{a.get('content', '')}".strip(),
+        "tags": a.get("tags", ""),
+        "dimensions": a.get("dimensions", ""),
+        "pub_date": a.get("updatedAt", ""),
+    }
+
+
+# 同步互斥锁:防止定时任务与手动触发并发写同一 Chroma collection。
+# gunicorn 单 worker 单事件循环下 asyncio.Lock 足够;两任务并发曾导致
+# microbiome 块被相互删除(缺 844 块),加锁后后到者直接跳过。
+_sync_lock = asyncio.Lock()
+
+
+async def sync_knowledge_base():
+    """同步三个数据源: article/microbiome/dan_knowledge 全量重建到 cfc_knowledge。
+
+    加并发锁(后到者跳过);每源独立失败隔离;全部成功后更新 .sync_state。
+    """
+    if _sync_lock.locked():
+        logger.info("已有知识库同步任务进行中,本次触发跳过")
+        return
+    async with _sync_lock:
+        await _do_sync()
+
+
+async def _do_sync():
+    loader = KnowledgeLoader()
+    splitter = get_knowledge_splitter()
+    embeddings = get_embeddings()
+
+    vectorstore = Chroma(
+        collection_name="cfc_knowledge",
+        embedding_function=embeddings,
+        persist_directory=settings.chroma_db_path,
+    )
+
+    state = _load_sync_state()
+    stats: dict = {}
+
+    async def fetch_articles():
+        articles = await loader.load_all_articles()
+        return [_format_article_item(a) for a in articles if a.get("id") is not None]
+
+    stats["article"] = await _sync_source(vectorstore, splitter, "article", fetch_articles)
+    stats["microbiome"] = await _sync_source(
+        vectorstore, splitter, "microbiome", loader.java.get_microbiome_articles)
+    stats["dan_knowledge"] = await _sync_source(
+        vectorstore, splitter, "dan_knowledge", loader.java.get_dan_knowledge_base)
+
+    if not any(stats.values()):
+        logger.warning("知识库同步: 全部数据源失败,不更新 last_sync")
+        return
+
+    state["last_sync"] = datetime.datetime.now().isoformat()
+    _save_sync_state(state)
+    logger.info("知识库同步完成: 各源块数 %s", stats)

+ 1 - 0
cfc-langgraph/app/tools/__init__.py

@@ -0,0 +1 @@
+from .java_client import JavaClient

+ 284 - 0
cfc-langgraph/app/tools/java_client.py

@@ -0,0 +1,284 @@
+import httpx
+from typing import Optional
+from app.config import settings
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class JavaClient:
+    """Java 后端 HTTP 客户端 (单例, 复用连接池)"""
+
+    _instance: Optional["JavaClient"] = None
+
+    def __new__(cls):
+        if cls._instance is None:
+            cls._instance = super().__new__(cls)
+            cls._instance._client = None
+            cls._instance._base_url = settings.java_base_url
+        return cls._instance
+
+    async def _get_client(self) -> httpx.AsyncClient:
+        if self._client is None:
+            limits = httpx.Limits(
+                max_connections=10,
+                max_keepalive_connections=5,
+                keepalive_expiry=30,
+            )
+            self._client = httpx.AsyncClient(
+                base_url=self._base_url,
+                timeout=httpx.Timeout(120.0, connect=3.0),
+                limits=limits,
+            )
+        return self._client
+
+    async def close(self):
+        if self._client:
+            await self._client.aclose()
+            self._client = None
+            JavaClient._instance = None
+
+    async def get_published_articles(self) -> list[dict]:
+        """拉取已发布知识库文章(分页 + records 解析,避免单次响应过大 / 返回 dict 结构)"""
+        client = await self._get_client()
+        page = 1
+        size = 50
+        records = []
+        while True:
+            resp = await client.post("/api/article/list", json={"status": "published", "page": page, "size": size})
+            data = resp.json()
+            if data.get("code") != 200:
+                break
+            body = data.get("data", {}) or {}
+            items = body.get("records", []) or []
+            records.extend(items)
+            total = body.get("total", 0)
+            if page * size >= int(total or 0) or not items:
+                break
+            page += 1
+        return records
+
+    async def search_products(self, keyword: str, limit: int = 5) -> list[dict]:
+        client = await self._get_client()
+        resp = await client.post("/api/product/search", json={
+            "keyword": keyword, "status": "上架", "limit": limit
+        })
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def search_activities(self, keyword: str, limit: int = 5) -> list[dict]:
+        client = await self._get_client()
+        resp = await client.post("/api/activity/search", json={
+            "keyword": keyword, "status": "published", "limit": limit
+        })
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def search_articles(self, keyword: str, limit: int = 5) -> list[dict]:
+        client = await self._get_client()
+        resp = await client.post("/api/article/search", json={
+            "keyword": keyword, "status": "published", "limit": limit
+        })
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def get_user_context(self, user_id: int, params: Optional[dict] = None) -> dict:
+        client = await self._get_client()
+        resp = await client.post(settings.effective_java_context_url, json={
+            "user_id": str(user_id),
+            "params": params or {},
+        })
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", {})
+        return {}
+
+    @staticmethod
+    def _join_metadata(value) -> str:
+        """把后端返回的标签/维度数组或字符串统一为 Chroma metadata 字符串。"""
+        if value is None:
+            return ""
+        if isinstance(value, str):
+            return value
+        if isinstance(value, (list, tuple, set)):
+            return ",".join(str(item) for item in value if item)
+        return str(value)
+
+    @classmethod
+    def _map_dan_knowledge(cls, record: dict) -> dict:
+        """dan_knowledge_base 字段(camelCase) → loader/_build_chunks 所需结构。"""
+        return {
+            "id": record.get("id"),
+            "title": record.get("title") or "",
+            "content": record.get("content") or "",
+            "category": "",
+            "tags": cls._join_metadata(record.get("tagNames") or record.get("tags")),
+            "dimensions": cls._join_metadata(
+                record.get("dimensionCodes") or record.get("dimensions")),
+            "source_url": record.get("sourceUrl") or "",
+            "pub_date": str(record.get("createdAt") or record.get("updatedAt") or ""),
+        }
+
+    async def get_microbiome_articles(self) -> list[dict]:
+        """拉取菌群知识库文章(统一数据源 dan_knowledge_base,source_type='article')
+
+        2026-10-20 迁移:microbiome_article 表废弃,809 篇菌群知识统一到
+        dan_knowledge_base 管理。分页拉 /api/admin/knowledge-base/list,
+        ORDER BY id 稳定分页,避免跨页重复。标签/维度由后端批量回填。
+        """
+        client = await self._get_client()
+        page = 1
+        size = 50
+        records = []
+        while True:
+            resp = await client.post("/api/admin/knowledge-base/list",
+                                     json={"page": page, "size": size, "status": 1, "sourceType": "article"})
+            data = resp.json()
+            if data.get("code") != 200:
+                break
+            body = data.get("data", {}) or {}
+            items = body.get("records", []) or []
+            records.extend(items)
+            total = body.get("total", 0)
+            if page * size >= int(total or 0) or not items:
+                break
+            page += 1
+        return [
+            self._map_dan_knowledge(r) for r in records if r.get("id") is not None
+        ]
+
+    async def get_dan_knowledge_base(self) -> list[dict]:
+        """拉取案例报告源(dan_knowledge_base 表,status=1,排除 article 菌群文章)
+
+        若 article 为 0 条(INSERT 前确实为 0),则该源拉 0 条,正常。
+        返回结构包含 content/tags/dimensions,供 Chroma metadata 使用。
+        """
+        client = await self._get_client()
+        page = 1
+        size = 1000
+        records = []
+        while True:
+            resp = await client.post("/api/admin/knowledge-base/list", json={"page": page, "size": size, "status": 1, "excludeSourceType": "article"})
+            data = resp.json()
+            if data.get("code") != 200:
+                break
+            body = data.get("data", {}) or {}
+            items = body.get("records", []) or []
+            records.extend(items)
+            total = body.get("total", 0)
+            if page * size >= int(total or 0) or not items:
+                break
+            page += 1
+        return [
+            self._map_dan_knowledge(r) for r in records if r.get("id") is not None
+        ]
+
+    async def get_member_reports(self, member_id: int) -> list[dict]:
+        """获取某个家庭成员的健康报告列表"""
+        client = await self._get_client()
+        resp = await client.post("/api/health/report/list", json={"memberId": member_id})
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def get_report_indicators(self, report_id: int) -> list[dict]:
+        """获取健康报告的所有指标明细"""
+        client = await self._get_client()
+        resp = await client.post("/api/health/report/indicator/list", json={"reportId": report_id})
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def get_report_detail_json(self, report_id: int) -> dict:
+        """获取报告完整详情(含「疾病相关菌」区块,供加权食材推荐)。
+
+        依赖后端 /api/health/report/detail 返回 data 内带「疾病相关菌」(或
+        Java 归一化别名 diseaseRelated);后端尚未补齐该字段时返回 {},
+        调用方据此静默降级,不抛异常、不阻断方案生成主链路。
+        """
+        client = await self._get_client()
+        try:
+            resp = await client.post("/api/health/report/detail", json={"reportId": report_id})
+            data = resp.json()
+            if data.get("code") == 200 and isinstance(data.get("data"), dict):
+                return data["data"]
+        except Exception as e:
+            logger.warning("获取报告详情 JSON 失败(reportId=%s): %s", report_id, e)
+        return {}
+
+    async def query_health_knowledge(self, item_type: str, item_name: str) -> dict | None:
+        """查询健康知识库中某个指标/菌属/营养素的定义"""
+        client = await self._get_client()
+        resp = await client.post("/api/health/knowledge/query", json={
+            "itemType": item_type, "itemName": item_name,
+        })
+        data = resp.json()
+        if data.get("code") == 200 and data.get("data"):
+            return data["data"]
+        return None
+
+    async def batch_query_health_knowledge(self, queries: list[dict]) -> list[dict]:
+        """批量查询健康知识库"""
+        client = await self._get_client()
+        resp = await client.post("/api/health/knowledge/batch-query", json={"queries": queries})
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+
+    async def get_family_context(self, user_id: int, intent_type: str = "child_info", params: dict | None = None) -> dict:
+        """获取家庭上下文数据(通过公开的 /api/ai/context 端点)"""
+        client = await self._get_client()
+        body = {"user_id": str(user_id), "intent_type": intent_type}
+        if params:
+            body["params"] = params
+        resp = await client.post("/api/ai/context", json=body)
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", {})
+        return {}
+
+    async def get_member_profile(self, member_id: int) -> dict:
+        """获取家庭成员画像快照"""
+        client = await self._get_client()
+        resp = await client.post("/api/profile/my", json={"memberId": member_id})
+        data = resp.json()
+        if data.get("code") == 200 and data.get("data"):
+            return data["data"]
+        return {}
+
+    async def get_member_health_status(self, member_id: int) -> dict:
+        """获取家庭成员健康自检问卷(health_status,内部端点无用户归属校验)"""
+        client = await self._get_client()
+        resp = await client.post("/api/health-status/internal/get", json={"memberId": member_id})
+        data = resp.json()
+        if data.get("code") == 200 and data.get("data"):
+            return data["data"]
+        return {}
+
+    async def get_member_diet_preferences(self, member_id: int) -> dict:
+        """获取家庭成员饮食偏好(diet_preferences,含饮食结构现状)"""
+        client = await self._get_client()
+        resp = await client.post("/api/diet/preferences/current-member", json={"memberId": member_id})
+        data = resp.json()
+        if data.get("code") == 200 and data.get("data"):
+            return data["data"]
+        return {}
+
+    async def get_member_indicator_current(self, member_id: int) -> list[dict]:
+        """获取成员指标当前值+相对上次变化(member_indicator_current,含 delta/trend)"""
+        client = await self._get_client()
+        resp = await client.post("/api/health/indicators/current", json={"memberId": member_id})
+        data = resp.json()
+        if data.get("code") == 200:
+            return data.get("data", [])
+        return []
+

+ 58 - 0
cfc-langgraph/app/tools/product_tools.py

@@ -0,0 +1,58 @@
+from langchain_core.tools import tool
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+_java = JavaClient()
+
+
+@tool
+async def search_product_by_keyword(keyword: str, limit: int = 5) -> str:
+    """按关键词搜索上架商品, 返回 JSON 商品列表"""
+    try:
+        products = await _java.search_products(keyword, limit)
+        if not products:
+            return "[]"
+        return str([{
+            "id": p["id"],
+            "name": p["name"],
+            "price": p.get("price"),
+            "description": p.get("intro") or p.get("description", ""),
+        } for p in products])
+    except Exception as e:
+        logger.warning("搜索商品失败: %s", e)
+        return "[]"
+
+
+@tool
+async def search_activity_by_keyword(keyword: str, limit: int = 5) -> str:
+    """按关键词搜索进行中的活动, 返回 JSON 活动列表"""
+    try:
+        activities = await _java.search_activities(keyword, limit)
+        if not activities:
+            return "[]"
+        return str([{
+            "id": a["id"],
+            "name": a["title"],
+            "description": a.get("description", ""),
+        } for a in activities])
+    except Exception as e:
+        logger.warning("搜索活动失败: %s", e)
+        return "[]"
+
+
+@tool
+async def search_article_by_keyword(keyword: str, limit: int = 5) -> str:
+    """按关键词搜索已发布文章, 返回 JSON 文章列表"""
+    try:
+        articles = await _java.search_articles(keyword, limit)
+        if not articles:
+            return "[]"
+        return str([{
+            "id": a["id"],
+            "name": a["title"],
+            "summary": a.get("summary", ""),
+        } for a in articles])
+    except Exception as e:
+        logger.warning("搜索文章失败: %s", e)
+        return "[]"

+ 63 - 0
cfc-langgraph/app/tools/report_tools.py

@@ -0,0 +1,63 @@
+from langchain_core.tools import tool
+from app.tools.java_client import JavaClient
+import logging
+
+logger = logging.getLogger(__name__)
+_java = JavaClient()
+
+
+@tool
+async def get_report_detail(report_id: int) -> str:
+    """获取健康报告的完整详情, 包含各维度评分和解读"""
+    try:
+        client = _java
+        resp = await client._get_client().post(
+            "/api/health/report/detail",
+            json={"reportId": report_id},
+        )
+        data = resp.json()
+        if data.get("code") == 200:
+            import json
+            return json.dumps(data.get("data", {}), ensure_ascii=False)
+        return "{}"
+    except Exception as e:
+        logger.warning("获取报告详情失败: %s", e)
+        return "{}"
+
+
+@tool
+async def get_survey_data(report_id: int) -> str:
+    """获取与报告关联的调研问卷数据"""
+    try:
+        client = _java
+        resp = await client._get_client().post(
+            "/api/survey/completed",
+            json={"reportId": report_id},
+        )
+        data = resp.json()
+        if data.get("code") == 200:
+            import json
+            return json.dumps(data.get("data", {}), ensure_ascii=False)
+        return "{}"
+    except Exception as e:
+        logger.warning("获取问卷数据失败: %s", e)
+        return "{}"
+
+
+@tool
+async def get_dimension_scores(family_id: int) -> str:
+    """获取家庭成员的五维能量分数 (身/心/智/行/富)"""
+    try:
+        client = _java
+        resp = await client._get_client().post(
+            "/api/dimension/scores",
+            json={"familyId": family_id},
+        )
+        data = resp.json()
+        if data.get("code") == 200:
+            import json
+            return json.dumps(data.get("data", {}), ensure_ascii=False)
+        return "{}"
+    except Exception as e:
+        logger.warning("获取维度分数失败: %s", e)
+        return "{}"

+ 17 - 0
cfc-langgraph/conftest.py

@@ -0,0 +1,17 @@
+"""Root-level conftest to patch ctranslate2 before tests import app.main."""
+import sys
+
+
+class _MockModels:
+    class WhisperGenerationResult:
+        pass
+
+
+class _MockCTranslate2:
+    StorageView = type("StorageView", (), {})
+    models = _MockModels()
+
+
+# Install mock before any real import of ctranslate2
+if "ctranslate2" not in sys.modules:
+    sys.modules["ctranslate2"] = _MockCTranslate2()

+ 44 - 0
cfc-langgraph/deploy.sh

@@ -0,0 +1,44 @@
+#!/bin/bash
+# LangGraph 部署脚本
+# 用法: ./deploy.sh
+#
+# 说明:
+#   cfc-langgraph 以 Docker 镜像方式部署 —— Dockerfile 在构建时把 app/ 等代码 COPY 进镜像,
+#   因此代码变更必须「重新 build 镜像 + 重建容器」才能生效;仅 restart 不会加载新代码。
+#   本脚本在服务器上就地执行(服务地址 https://ai.etotem.com.cn,容器端口 9000)。
+#
+# 历史:旧版本 rsync 到 /opt/sc-data/cfc/cfc-langgraph 后执行 docker-compose restart,
+#   该路径已不存在,且 restart 无法更新镜像,故重写为就地 build + up。
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+cd "$SCRIPT_DIR"
+
+echo "=== LangGraph Deploy ==="
+echo "目录: $SCRIPT_DIR"
+
+echo "[1/3] 构建镜像 (langgraph-svc)..."
+docker compose build langgraph-svc
+
+echo "[2/3] 重建并启动服务..."
+docker compose up -d langgraph-svc
+
+echo "[3/3] 健康检查..."
+ok=0
+for i in $(seq 1 30); do
+  if curl -sf "https://ai.etotem.com.cn/health" > /dev/null 2>&1; then
+    ok=1
+    break
+  fi
+  echo "  等待服务就绪 ($i/30)..."
+  sleep 5
+done
+
+if [ "$ok" = "1" ]; then
+  echo "✅ 部署成功!服务地址: https://ai.etotem.com.cn"
+  curl -s "https://ai.etotem.com.cn/api/v1/health" | python3 -m json.tool 2>/dev/null || true
+else
+  echo "❌ 健康检查失败,请查看日志: docker compose -f ${SCRIPT_DIR}/docker-compose.yml logs langgraph-svc --tail=50"
+  exit 1
+fi

+ 71 - 0
cfc-langgraph/docker-compose.yml

@@ -0,0 +1,71 @@
+version: "3.8"
+
+services:
+  cfc-backend:
+    build:
+      context: ../cfc-backend
+      dockerfile: Dockerfile
+    ports:
+      - "9082:9082"
+    environment:
+      - SPRING_PROFILES_ACTIVE=prod
+      - python.enabled=true
+      - python.base-url=http://langgraph-svc:9000
+    networks:
+      - cfc-net
+    restart: unless-stopped
+    healthcheck:
+      test: ["CMD", "curl", "-f", "http://localhost:9082/actuator/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+
+  langgraph-svc:
+    image: cfc-langgraph-langgraph-svc:v10.3
+    build:
+      context: .
+      dockerfile: Dockerfile
+    ports:
+      - "9000:9000"
+    env_file:
+      - .env.production
+    environment:
+      - JAVA_BASE_URL=http://172.17.0.1:9082
+      - JAVA_CONTEXT_URL=http://172.17.0.1:9082/api/ai/context
+      - CHROMA_DB_PATH=/data/chroma_db
+      - JSON_LOGS=true
+      # LangSmith 三个变量从 env_file (.env.production) 读取,不再覆盖
+    volumes:
+      # 共享 Java 文件上传目录(LangGraph 读取已上传的 PDF 文件)
+      - /data/cfc-uploads:/data/cfc-uploads
+      # Chroma 向量数据库持久化
+      - langgraph-data:/data/chroma_db
+    networks:
+      - cfc-net
+    restart: unless-stopped
+    # 内存硬限制:防止 ChromaDB/搜索任务异常膨胀吃满宿主机内存导致整机 OOM
+    mem_limit: 8g
+    healthcheck:
+      test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:9000/health', timeout=5).status==200 else 1)"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+
+
+  prometheus:
+    image: prom/prometheus:latest
+    volumes:
+      - ./prometheus.yml:/etc/prometheus/prometheus.yml
+      - prometheus-data:/prometheus
+    networks:
+      - cfc-net
+    restart: unless-stopped
+    profiles:
+      - monitoring
+
+networks:
+  cfc-net:
+
+volumes:
+  langgraph-data:
+  prometheus-data:

+ 97 - 0
cfc-langgraph/docs/deployment.md

@@ -0,0 +1,97 @@
+# LangGraph Sidecar 部署文档
+
+## 前置依赖
+
+- Docker + Docker Compose (推荐)
+- 或 Python 3.11+ + pip (直接部署)
+- LLM API Key (DeepSeek / OpenAI 兼容)
+
+## 目录结构
+
+```
+cfc-langgraph/
+├── Dockerfile
+├── docker-compose.yml
+├── prometheus.yml
+├── .env.production          # 生产配置 (手动创建, 不上传 git)
+├── app/                     # 服务代码
+│   ├── main.py              # FastAPI 入口
+│   ├── config.py            # 配置管理
+│   ├── api/                 # HTTP 接口
+│   ├── agents/              # Agent 定义
+│   ├── graphs/              # LangGraph StateGraph
+│   ├── tools/               # Agent Tool
+│   ├── rag/                 # RAG Pipeline
+│   ├── memory/              # 三层记忆
+│   └── tasks/               # 定时任务
+├── data/
+│   └── chroma_db/           # ChromaDB 持久化 (自动创建)
+└── docs/
+    ├── deployment.md        # 本文件
+    └── operations.md        # 运维手册
+```
+
+## Docker Compose 部署
+
+```bash
+# 1. 创建生产配置
+cp .env.example .env.production
+# 编辑 .env.production 填入 LLM_API_KEY
+
+# 2. 构建并启动
+docker-compose up -d
+
+# 3. 验证
+curl http://localhost:9000/api/v1/health
+
+# 4. 查看日志
+docker-compose logs -f langgraph-svc
+```
+
+## 直接部署 (无 Docker)
+
+```bash
+# 1. 安装依赖
+pip install -e .
+
+# 2. 配置环境变量
+export LLM_API_KEY=sk-xxx
+export JAVA_BASE_URL=http://localhost:9082
+
+# 3. 启动
+gunicorn app.main:app \
+  --worker-class uvicorn.workers.UvicornWorker \
+  --bind 0.0.0.0:9000 \
+  --workers 2 \
+  --timeout 60 \
+  --access-logfile - \
+  --error-logfile -
+```
+
+## 环境变量说明
+
+| 变量 | 必填 | 说明 |
+|------|------|------|
+| LLM_API_KEY | 是 | LLM API Key |
+| LLM_BASE_URL | 否 | 默认 https://api.deepseek.com/v1 |
+| LLM_MODEL | 否 | 默认 deepseek-chat |
+| JAVA_BASE_URL | 是 | Java 后端地址 |
+| CHROMA_DB_PATH | 否 | ChromaDB 持久化路径, 默认 ./data/chroma_db |
+| LOG_LEVEL | 否 | 日志级别, 默认 info |
+| JSON_LOGS | 否 | 启用 JSON 日志格式, 默认 false |
+
+## 健康检查
+
+```
+GET /api/v1/health
+
+Response:
+{
+  "status": "ok",
+  "components": {
+    "chromadb": {"status": "ok", "path": "...", "exists": true},
+    "llm": {"status": "ok"},
+    "java_backend": {"status": "ok"}
+  }
+}
+```

+ 121 - 0
cfc-langgraph/docs/operations.md

@@ -0,0 +1,121 @@
+# LangGraph Sidecar 运维手册
+
+## 日常监控
+
+### 1. 健康检查
+
+生产环境建议配置 30 秒定时健康检查:
+
+```bash
+curl -f http://localhost:9000/api/v1/health
+```
+
+预期返回 `{"status":"ok"}`。组件降级时返回 `{"status":"degraded"}`。
+
+### 2. Prometheus 指标
+
+```
+GET /metrics
+
+关键指标:
+- agent_calls_total{agent_type="chat|recommend|analysis"}
+- agent_duration_seconds{agent_type="..."}
+- llm_calls_total{model="deepseek-chat",status="ok|error"}
+- llm_duration_seconds{model="..."}
+- kb_sync_duration_seconds        # 知识库同步耗时
+```
+
+### 3. 日志
+
+JSON 格式日志可直接接入 ELK / Loki:
+
+```json
+{"timestamp":"2026-07-20T10:00:00","level":"WARN","logger":"app.main","message":"SLOW_REQUEST: POST /api/v1/chat took 8.23s"}
+```
+
+## 常见问题
+
+### Python 服务无法启动
+
+```bash
+# 检查依赖
+pip list | grep -E "fastapi|langchain|langgraph"
+
+# 检查配置
+python -c "from app.config import settings; print(settings.llm_model)"
+
+# 检查端口占用
+netstat -ano | grep 9000
+```
+
+### LLM 调用失败
+
+1. 检查 `.env.production` 中的 `LLM_API_KEY` 是否有效
+2. 检查 `LLM_BASE_URL` 是否可访问
+3. 查看日志: `docker-compose logs langgraph-svc | grep llm_call`
+
+### ChromaDB 损坏
+
+```bash
+# 删除后重建 (知识库会自动同步)
+rm -rf data/chroma_db/
+docker-compose restart langgraph-svc
+
+# 或触发手动同步
+curl -X POST http://localhost:9000/api/v1/admin/kb-sync
+```
+
+### 知识库同步失败
+
+```bash
+# 检查 Java 后端是否可访问
+curl http://localhost:9082/health
+
+# 检查文章接口
+curl -X POST http://localhost:9082/api/article/updated-since \
+  -H "Content-Type: application/json" \
+  -d '{"since":"2026-01-01T00:00:00","status":"published"}'
+
+# 手动触发同步
+docker-compose exec langgraph-svc python -c "
+import asyncio
+from app.tasks.knowledge_sync import sync_knowledge_base
+asyncio.run(sync_knowledge_base())
+"
+```
+
+### Java 端回退 Dify
+
+如果 Python 服务异常, Java 会自动回退 Dify:
+
+```yaml
+# application.yml 检查配置
+python:
+  enabled: true
+  circuit-breaker:
+    failure-threshold: 3
+    reset-timeout-ms: 30000
+```
+
+熔断器打开时, Java 侧日志会输出 `AiGateway 熔断器已打开`, 等待 `reset-timeout-ms` 后自动半开重试。
+
+## 扩缩容
+
+LangGraph 服务是无状态的 (ChromaDB 在共享存储上):
+
+```yaml
+# docker-compose 增加副本数
+services:
+  langgraph-svc:
+    deploy:
+      replicas: 2
+```
+
+注意: ChromaDB 文件模式不支持并发写入, 多副本时知识库同步需加锁或切 PGVector。
+
+## 备份
+
+```bash
+# ChromaDB 数据
+tar czf chroma_backup_$(date +%Y%m%d).tar.gz data/chroma_db/
+```

+ 9 - 0
cfc-langgraph/prometheus.yml

@@ -0,0 +1,9 @@
+global:
+  scrape_interval: 15s
+  evaluation_interval: 15s
+
+scrape_configs:
+  - job_name: "langgraph-svc"
+    static_configs:
+      - targets: ["langgraph-svc:9000"]
+    metrics_path: /metrics

+ 48 - 0
cfc-langgraph/pyproject.toml

@@ -0,0 +1,48 @@
+[project]
+name = "cfc-langgraph"
+version = "0.1.0"
+description = "cfc AI sidecar service with LangGraph"
+requires-python = ">=3.11"
+dependencies = [
+    "fastapi>=0.115",
+    "uvicorn[standard]>=0.34",
+    "pydantic>=2.10",
+    "pydantic-settings>=2.7",
+    "httpx>=0.28",
+    "langchain>=0.3,<1.0",
+    "langchain-community>=0.3,<1.0",
+    "langchain-openai>=0.3,<1.0",
+    "langgraph>=0.3,<1.0",
+    "chromadb==0.5.23",
+    "langchain-chroma==0.1.4",
+    "python-multipart>=0.0.20",
+    "prometheus-client>=0.21",
+    "faster-whisper==1.2.1",
+    "av==18.1.0",
+]
+
+[project.optional-dependencies]
+dev = [
+    "pytest>=8",
+    "pytest-asyncio>=0.25",
+    "ruff>=0.8",
+    "httpx",
+]
+
+[tool.ruff]
+target-version = "py311"
+line-length = 100
+select = ["E", "F", "I", "N", "W"]
+ignore = ["E501"]
+
+[tool.pytest.ini_options]
+# pytest-asyncio 1.x 要求显式 loop scope;B-74 修复(2026-11-09):
+# session 级 autouse async fixture(conftest._init_checkpointer_global)需
+# session/auto 默认 loop scope 方能初始化 checkpointer 并无缝复用于全部测试。
+asyncio_mode = "auto"
+asyncio_default_fixture_loop_scope = "session"
+# B-117 修复:仅设 fixture loop scope 不够;测试函数本身默认 function scope,
+# 与 session-scoped checkpointer 跨 loop,触发 "Lock bound to different event loop"。
+# 将测试 loop 也提升到 session,让所有 async 测试共享同一事件循环,避免 AsyncSqliteSaver
+# 内部 Condition/Lock 绑定失效。
+asyncio_default_test_loop_scope = "session"

+ 21 - 0
cfc-langgraph/requirements.txt

@@ -0,0 +1,21 @@
+fastapi>=0.110,<1.0
+uvicorn[standard]>=0.29,<1.0
+langgraph>=0.2,<1.0
+langgraph-checkpoint-sqlite==3.0.3
+aiosqlite>=0.19,<1.0
+langchain-openai>=0.2,<1.0
+langchain-core>=0.3,<1.0
+chromadb==0.5.23
+langchain-chroma==0.1.4
+pydantic>=2.0,<3.0
+python-dotenv>=1.0,<2.0
+httpx>=0.27,<1.0
+pytest>=8.0,<9.0
+PyPDF2>=3.0,<4.0
+faster-whisper==1.2.1
+av==18.1.0
+Pillow>=10.0,<11.0
+# 情绪识别
+deepface>=0.0.90
+opencv-python-headless>=4.8,<5.0
+numpy>=1.24,<2.0

+ 125 - 0
cfc-langgraph/requirements_frozen.txt

@@ -0,0 +1,125 @@
+aiohappyeyeballs==2.7.1
+aiohttp==3.14.2
+aiosignal==1.4.0
+aiosqlite==0.22.1
+annotated-doc==0.0.4
+annotated-types==0.7.0
+anyio==4.14.2
+attrs==26.1.0
+bcrypt==5.0.0
+build==1.5.0
+certifi==2026.6.17
+charset-normalizer==3.4.9
+chromadb==1.5.9
+click==8.4.2
+dataclasses-json==0.6.7
+distro==1.9.0
+durationpy==0.10
+fastapi==0.139.2
+filelock==3.31.1
+flatbuffers==25.12.19
+frozenlist==1.8.0
+fsspec==2026.6.0
+googleapis-common-protos==1.75.0
+greenlet==3.5.3
+grpcio==1.82.1
+gunicorn==26.0.0
+h11==0.16.0
+hf-xet==1.5.2
+httpcore==1.0.9
+httptools==0.8.0
+httpx==0.28.1
+httpx-sse==0.4.3
+huggingface_hub==1.24.0
+idna==3.18
+importlib_resources==7.1.0
+iniconfig==2.3.0
+jiter==0.16.0
+jsonpatch==1.33
+jsonpointer==3.1.1
+jsonschema==4.26.0
+jsonschema-specifications==2025.9.1
+kubernetes==36.0.3
+langchain==0.3.30
+langchain-chroma==0.2.6
+langchain-classic==1.0.8
+langchain-community==0.3.31
+langchain-core==0.3.86
+langchain-openai==0.3.35
+langchain-protocol==0.0.18
+langchain-text-splitters==0.3.11
+langgraph==0.6.11
+langgraph-checkpoint==3.0.1
+langgraph-checkpoint-sqlite==3.0.3
+langgraph-prebuilt==0.6.5
+langgraph-sdk==0.2.15
+langsmith==0.10.9
+markdown-it-py==4.2.0
+marshmallow==3.26.2
+mdurl==0.1.2
+mmh3==5.2.1
+multidict==6.7.1
+mypy_extensions==1.1.0
+numpy==1.26.4
+oauthlib==3.3.1
+onnxruntime==1.27.0
+openai==2.46.0
+opentelemetry-api==1.44.0
+opentelemetry-exporter-otlp-proto-common==1.44.0
+opentelemetry-exporter-otlp-proto-grpc==1.44.0
+opentelemetry-proto==1.44.0
+opentelemetry-sdk==1.44.0
+opentelemetry-semantic-conventions==0.65b0
+orjson==3.11.9
+ormsgpack==1.12.2
+overrides==7.7.0
+packaging==25.0
+pluggy==1.6.0
+prometheus_client==0.25.0
+propcache==0.5.2
+protobuf==7.35.1
+pybase64==1.4.3
+pydantic==2.13.4
+pydantic-settings==2.14.2
+pydantic_core==2.46.4
+Pygments==2.20.0
+PyPDF2==3.0.1
+PyPika==0.51.1
+pyproject_hooks==1.2.0
+pytest==8.4.2
+pytest-asyncio==1.4.0
+python-dateutil==2.9.0.post0
+python-dotenv==1.2.2
+python-multipart==0.0.32
+PyYAML==6.0.3
+referencing==0.37.0
+regex==2026.7.19
+requests==2.34.2
+requests-oauthlib==2.0.0
+requests-toolbelt==1.0.0
+rich==15.0.0
+rpds-py==2026.6.3
+sentence-transformers==5.7.0
+shellingham==1.5.4
+six==1.17.0
+sniffio==1.3.1
+SQLAlchemy==2.0.51
+starlette==1.3.1
+tenacity==9.1.4
+tiktoken==0.13.0
+tokenizers==0.23.1
+tqdm==4.69.0
+typer==0.27.0
+typing-inspect==0.9.0
+typing-inspection==0.4.2
+typing_extensions==4.16.0
+urllib3==2.7.0
+uuid_utils==0.17.0
+uvicorn==0.51.0
+uvloop==0.22.1
+watchfiles==1.2.0
+websocket-client==1.9.0
+websockets==15.0.1
+xxhash==3.8.1
+yarl==1.24.5
+zstandard==0.25.0

+ 82 - 0
cfc-langgraph/scripts/run_pytest.sh

@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# run_pytest.sh — R376-lg-venv 闭环脚本
+#
+# 修复两个缺口:
+#   G-376-1(P0):系统 python3 = 3.6.8,无 pytest 模块;必须显式走 .venv/bin/python。
+#   G-376-2(P1):timeout 360 被 B-325-1 进程驻留强杀于汇总前;
+#                  改用 timeout 600 + tee 落盘 + 汇总行 grep 兜底。
+#
+# 用法:
+#   ./scripts/run_pytest.sh                        # 默认跑 tests/ 全量,超时 600s
+#   ./scripts/run_pytest.sh tests/test_intent.py   # 指定单文件或目录
+#   TIMEOUT_SEC=900 ./scripts/run_pytest.sh        # 自定义超时
+#
+# 输出:
+#   stdout          实时回显
+#   /tmp/r{run_id}_lg.log   完整日志(包含汇总行,供grep兜底)
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+VENV_PY="${REPO_ROOT}/.venv/bin/python"
+LOG_DIR="/tmp"
+RUN_ID="$(date +%Y%m%d-%H%M%S)"
+LOG_FILE="${LOG_DIR}/r${RUN_ID}_lg.log"
+
+TIMEOUT_SEC="${TIMEOUT_SEC:-600}"
+
+# ── G-376-1 检查:解释器必须来自 venv ────────────────────────────────
+if [[ ! -x "${VENV_PY}" ]]; then
+    echo "ERROR: ${VENV_PY} not found. Run: source .venv/bin/activate" >&2
+    exit 1
+fi
+PYVER="$("${VENV_PY}" --version 2>&1)"
+echo "[r376-lg-venv] interpreter : ${VENV_PY}"
+echo "[r376-lg-venv] python      : ${PYVER}"
+
+# ── 收集测试参数 ──────────────────────────────────────────────────────
+shift || true
+TEST_PATHS="$*"
+if [[ -z "${TEST_PATHS}" ]]; then
+    TEST_PATHS="tests"
+fi
+
+# ── 健康探针(服务未起则跳过,不影响 ASGITransport 测试运行) ──────────
+curl -sf --max-time 3 http://127.0.0.1:9000/health >/dev/null 2>&1 \
+    && echo "[r376-lg-venv] service health: ok" \
+    || echo "[r376-lg-venv] service /health unreachable (ASGITransport 可独立运行)"
+
+# ── G-376-2 执行:timeout 600 + tee 落盘 ──────────────────────────────
+echo "[r376-lg-venv] running: ${VENV_PY} -m pytest ${TEST_PATHS} -q --tb=line"
+echo "[r376-lg-venv] log file : ${LOG_FILE}"
+echo "[r376-lg-venv] timeout  : ${TIMEOUT_SEC}s"
+
+EXIT_CODE=0
+timeout "${TIMEOUT_SEC}" \
+    "${VENV_PY}" -m pytest ${TEST_PATHS} -q --tb=line 2>&1 \
+    | tee "${LOG_FILE}" \
+    || EXIT_CODE=$?
+
+# ── 兜底:从日志文件提取汇总行(stdout 可能已被截断) ─────────────────
+SUMMARY=""
+if [[ -f "${LOG_FILE}" ]]; then
+    SUMMARY=$(grep -E "(passed|failed|error|collected)" "${LOG_FILE}" \
+              | tail -5 || true)
+fi
+
+echo ""
+echo "===== r376-lg-venv summary ====="
+echo "exit_code : ${EXIT_CODE}"
+echo "log_file  : ${LOG_FILE}"
+echo "summary   :"
+[[ -n "${SUMMARY}" ]] && echo "${SUMMARY}" | sed 's/^/  /' || echo "  (no summary line — check ${LOG_FILE})"
+echo "================================"
+
+if [[ ${EXIT_CODE} -eq 124 ]]; then
+    echo "WARNING: timeout reached (${TIMEOUT_SEC}s). Check ${LOG_FILE}."
+elif [[ ${EXIT_CODE} -ne 0 ]]; then
+    echo "FAIL: pytest exited with code ${EXIT_CODE}."
+fi
+
+exit ${EXIT_CODE}

+ 0 - 0
cfc-langgraph/src/__init__.py


+ 89 - 0
cfc-langgraph/src/app.py

@@ -0,0 +1,89 @@
+import json
+from datetime import datetime
+
+from dotenv import load_dotenv
+load_dotenv()
+
+from fastapi import APIRouter, FastAPI
+from fastapi.responses import JSONResponse
+
+from .schemas.questionnaire import GenerateRequest, GenerateResponse
+from .graphs.questionnaire import get_questionnaire_graph
+from .schemas.emotion import EmotionRequest, EmotionResponse, EmotionItem
+from .graphs.emotion import get_emotion_graph
+
+router = APIRouter(prefix="/api/v1", tags=["questionnaire"])
+
+
+@router.post("/questionnaire/generate")
+async def generate_questionnaire(req: GenerateRequest):
+    graph = get_questionnaire_graph()
+    try:
+        result = graph.invoke({
+            "request": req,
+            "raw_response": "",
+            "questionnaire": None,
+            "error": None,
+        })
+        if result.get("error"):
+            return JSONResponse(
+                status_code=500,
+                content={"error": result["error"]}
+            )
+        version = datetime.now().strftime("%Y%m%d%H%M%S")
+        return GenerateResponse(
+            questionnaire_json=json.dumps(result["questionnaire"], ensure_ascii=False),
+            version=version,
+        )
+    except Exception as e:
+        return JSONResponse(
+            status_code=500,
+            content={"error": f"graph 执行失败: {str(e)}"}
+        )
+
+
+app = FastAPI(title="CFC LangGraph 问卷生成服务")
+app.include_router(router)
+
+
+@app.get("/health")
+def health():
+    return {"status": "ok"}
+
+
+# ── 情绪识别 ─────────────────────────────────────────────────
+
+@router.post("/emotion/recognize")
+async def recognize_emotion(req: EmotionRequest):
+    graph = get_emotion_graph()
+    try:
+        result = graph.invoke({
+            "request": req.model_dump(),
+            "image_bytes": None,
+            "image_path": None,
+            "emotion_result": None,
+            "emotions": [],
+            "dominant_emotion": "neutral",
+            "dominant_label_zh": "平静",
+            "all_emotions": {},
+            "error": None,
+        })
+        if result.get("error"):
+            return JSONResponse(
+                status_code=400,
+                content={"error": result["error"]}
+            )
+        return EmotionResponse(
+            emotions=[
+                EmotionItem(emotion=e["emotion"], confidence=e["confidence"])
+                for e in result["emotions"]
+            ],
+            dominant_emotion=result["dominant_emotion"],
+            dominant_label_zh=result["dominant_label_zh"],
+            all_emotions=result["all_emotions"],
+        )
+    except Exception as e:
+        return JSONResponse(
+            status_code=500,
+            content={"error": f"graph 执行失败: {str(e)}"}
+        )

+ 2 - 0
cfc-langgraph/src/graphs/__init__.py

@@ -0,0 +1,2 @@
+from .emotion import get_emotion_graph, EMOTION_ZH  # noqa: F401
+from .tongue import get_tongue_graph  # noqa: F401

+ 177 - 0
cfc-langgraph/src/graphs/emotion.py

@@ -0,0 +1,177 @@
+"""
+情绪识别 LangGraph — DeepFace 人脸情绪分析
+
+流程:
+  START → detect_faces → analyze_emotion → END
+
+输出:7 类基础情绪概率 + 主导情绪 + 中文标签
+"""
+import base64
+import io
+import os
+from typing import TypedDict, Optional
+
+import requests
+from PIL import Image
+from langgraph.graph import StateGraph, START, END
+
+# DeepFace 延迟导入(未安装时 graceful fallback)
+try:
+    from deepface import DeepFace
+    DEEPFACE_AVAILABLE = True
+except ImportError:
+    DEEPFACE_AVAILABLE = False
+
+
+# ── 中文情绪映射 ──────────────────────────────────────────────
+EMOTION_ZH = {
+    "angry": "愤怒",
+    "disgust": "厌恶",
+    "fear": "恐惧",
+    "happy": "开心",
+    "sad": "悲伤",
+    "surprise": "惊讶",
+    "neutral": "平静",
+}
+
+
+# ── Graph State ───────────────────────────────────────────────
+class GraphState(TypedDict):
+    request: dict
+    image_bytes: Optional[bytes]       # 原始图片字节
+    image_path: Optional[str]          # 临时文件路径(供 DeepFace 使用)
+    emotion_result: Optional[dict]     # DeepFace analyze() 结果
+    emotions: list                     # 结构化输出
+    dominant_emotion: str
+    dominant_label_zh: str
+    all_emotions: dict                 # 7 类完整概率
+    error: Optional[str]
+
+
+# ── Nodes ─────────────────────────────────────────────────────
+
+def load_image(state: GraphState) -> GraphState:
+    """将 image_url 下载到内存 / 解码 base64"""
+    req = state["request"]
+    img_bytes = None
+
+    if req.get("image_url"):
+        try:
+            resp = requests.get(req["image_url"], timeout=10)
+            resp.raise_for_status()
+            img_bytes = resp.content
+        except Exception as e:
+            return {**state, "error": f"图片下载失败: {e}"}
+
+    elif req.get("image_base64"):
+        try:
+            img_bytes = base64.b64decode(req["image_base64"])
+        except Exception as e:
+            return {**state, "error": f"Base64 解码失败: {e}"}
+
+    else:
+        return {**state, "error": "image_url 或 image_base64 至少提供一项"}
+
+    if img_bytes:
+        state["image_bytes"] = img_bytes
+        # 写入临时文件供 DeepFace 使用
+        tmp_path = f"/tmp/emotion_{os.getpid()}.jpg"
+        with open(tmp_path, "wb") as f:
+            f.write(img_bytes)
+        state["image_path"] = tmp_path
+
+    return state
+
+
+def analyze_emotion(state: GraphState) -> GraphState:
+    """调用 DeepFace 进行情绪识别"""
+    if not DEEPFACE_AVAILABLE or not state.get("image_path"):
+        return {**state, "error": "DeepFace 未安装或图片未加载"}
+
+    try:
+        result = DeepFace.analyze(
+            img_path=state["image_path"],
+            actions=["emotion"],
+            detector_backend="opencv",   # 内置 Haar Cascade,无需额外模型
+            enforce_detection=False,
+            silent=True,
+        )
+        # DeepFace.analyze 返回 list(可能多张人脸)
+        if isinstance(result, list) and len(result) > 0:
+            state["emotion_result"] = result[0]
+        else:
+            return {**state, "error": "未检测到人脸"}
+    except Exception as e:
+        return {**state, "error": f"DeepFace 分析失败: {e}"}
+
+    return state
+
+
+def format_result(state: GraphState) -> GraphState:
+    """将 DeepFace 结果格式化为结构化输出"""
+    if not state.get("emotion_result"):
+        return state
+
+    emo = state["emotion_result"]
+    # DeepFace 返回 0-100 百分比(如 {'happy': 85.0, ...}),需归一化为 0.0-1.0
+    raw_emotions = emo.get("emotion", {})
+
+    # 归一化:值 >1 视为百分比,除以 100
+    norm = {}
+    for k, v in raw_emotions.items():
+        norm[k] = round(v / 100.0, 4) if v > 1.0 else round(v, 4)
+
+    # 找出主导情绪
+    dominant = max(norm, key=norm.get) if norm else "neutral"
+    dominant_zh = EMOTION_ZH.get(dominant, dominant)
+
+    # 结构化列表
+    emotions = [
+        {"emotion": k, "confidence": v}
+        for k, v in sorted(norm.items(), key=lambda x: -x[1])
+    ]
+
+    state["dominant_emotion"] = dominant
+    state["dominant_label_zh"] = dominant_zh
+    state["all_emotions"] = norm
+    state["emotions"] = emotions
+    return state
+
+
+def cleanup(state: GraphState) -> GraphState:
+    """清理临时文件"""
+    import os as _os
+    path = state.get("image_path")
+    if path and _os.path.exists(path):
+        try:
+            _os.remove(path)
+        except Exception:
+            pass
+    return state
+
+
+# ── Graph 构建 ────────────────────────────────────────────────
+
+def build_emotion_graph():
+    graph = StateGraph(GraphState)
+    graph.add_node("load_image", load_image)
+    graph.add_node("analyze_emotion", analyze_emotion)
+    graph.add_node("format_result", format_result)
+    graph.add_node("cleanup", cleanup)
+
+    graph.add_edge(START, "load_image")
+    graph.add_edge("load_image", "analyze_emotion")
+    graph.add_edge("analyze_emotion", "format_result")
+    graph.add_edge("format_result", "cleanup")
+    graph.add_edge("cleanup", END)
+    return graph.compile()
+
+
+_emotion_graph = None
+
+
+def get_emotion_graph():
+    global _emotion_graph
+    if _emotion_graph is None:
+        _emotion_graph = build_emotion_graph()
+    return _emotion_graph

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio