chat_workflow.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. """Chat orchestration without HTTP response objects (main.py split stage 4)."""
  2. from __future__ import annotations
  3. import json
  4. import re
  5. import sqlite3
  6. from dataclasses import dataclass, field
  7. from datetime import date, datetime
  8. from zoneinfo import ZoneInfo
  9. from hello_agents.core.exceptions import HelloAgentsException
  10. from starlette.concurrency import run_in_threadpool
  11. from fithealth_agent.context_budget import AGENT_INPUT_MAX_CHARS, ContextInputError
  12. from fithealth_agent.health_safety import (
  13. CAUTION, URGENT, RiskFinding, acute_pain_finding, emergency_reply,
  14. merge_findings, risk_directive, screen_health_risk, urgent_plan_block_note,
  15. )
  16. from fithealth_agent.info_store import (
  17. MemoryStoreDegradedError, fact_is_active, fact_retention_class,
  18. normalize_memory_facts, parse_weekly_schedule, resolve_confirmed_memory_facts,
  19. )
  20. from fithealth_agent.muscle_map import resolve_muscles_for_exercise
  21. from fithealth_agent.muscle_recovery import (
  22. MuscleRecoverySnapshot, build_recovery_snapshot,
  23. soreness_reply_needs_clarification,
  24. )
  25. from fithealth_agent.plan_workflow import PlanWorkflowState, state_after_generation
  26. from fithealth_agent.runtime import deps
  27. from fithealth_agent.runtime.deps import logger
  28. from fithealth_agent.runtime.responses import context_error_response
  29. from fithealth_agent.domain.intent_rules import (
  30. _is_safety_bypass_request, current_instruction_override, is_profile_query,
  31. is_training_record_query, is_training_related, navigation_only_message,
  32. )
  33. from fithealth_agent.domain.memory_view import (
  34. _memory_confirmation_decision,
  35. active_temporary_health_facts as _active_temporary_health_facts,
  36. confirmed_memory_profile as _confirmed_memory_profile,
  37. confirmed_weekly_schedule as _confirmed_weekly_schedule,
  38. format_cross_session_memories as _format_cross_session_memories,
  39. temporary_constraint_for_message, youtube_channels_to_avoid as _youtube_channels_to_avoid,
  40. )
  41. from fithealth_agent.domain.plan_context import (
  42. confirmed_weekly_schedule_entry, daily_schedule_constraint as _daily_schedule_constraint,
  43. format_plan_context, resolve_plan_context as _resolve_plan_context,
  44. scheduled_plan_for_message, scheduled_weekly_entry_for_message,
  45. )
  46. from fithealth_agent.domain.plan_validation import (
  47. extract_plan_subject, infer_plan_title, is_generic_training_subject,
  48. looks_like_complete_training_plan, most_recent_complete_training_plan,
  49. plan_card_title, plan_validation_fact_usage, validate_generated_training_plan,
  50. )
  51. from fithealth_agent.domain.profile_rules import (
  52. equipment_change_preview, merge_profile_updates_with_existing, onboarding_reply,
  53. profile_summary, validate_profile_tool_updates,
  54. )
  55. from fithealth_agent.domain.recovery_view import (
  56. _recovery_context_payload, _subject_recovery_regions,
  57. explicitly_requested_recovery_regions,
  58. )
  59. from fithealth_agent.domain.record_view import (
  60. _nutrition_record_date, _requested_record_date,
  61. _training_record_items,
  62. )
  63. @dataclass
  64. class ChatTurn:
  65. payload: dict[str, object]
  66. message: str
  67. history: list[dict]
  68. source: str
  69. profile: dict[str, object] = field(default_factory=dict)
  70. memories: list[dict] = field(default_factory=list)
  71. plan_context: dict[str, object] = field(default_factory=dict)
  72. artifacts: list[dict[str, object]] = field(default_factory=list)
  73. debug: dict[str, object] = field(default_factory=dict)
  74. @classmethod
  75. def from_payload(cls, payload: dict[str, object]) -> "ChatTurn":
  76. return cls(
  77. payload=payload,
  78. message=str(payload["message"]),
  79. history=list(payload["history"]),
  80. source=str(payload["source"]),
  81. )
  82. @dataclass(frozen=True)
  83. class ChatResult:
  84. body: dict[str, object]
  85. status_code: int = 200
  86. def stage_request_context(turn: ChatTurn) -> ChatTurn:
  87. """Initialize store-backed state after the route has validated the request."""
  88. turn.profile = deps.profile_store.get_profile()
  89. turn.debug["external_models_enabled"] = deps.external_model_settings_store.get()[
  90. "external_models_enabled"
  91. ]
  92. return turn
  93. def stage_health_safety(turn: ChatTurn) -> ChatTurn:
  94. """Named boundary for the health/soreness phase executed by the workflow."""
  95. return turn
  96. def stage_local_navigation(turn: ChatTurn) -> ChatTurn:
  97. """Named boundary for local record/profile navigation short circuits."""
  98. return turn
  99. def stage_intent_routing(turn: ChatTurn) -> ChatTurn:
  100. """Named boundary for constrained chat intent routing."""
  101. return turn
  102. def stage_plan_context(turn: ChatTurn) -> ChatTurn:
  103. """Named boundary for plan-context resolution and agent input assembly."""
  104. return turn
  105. def stage_postprocess(turn: ChatTurn) -> ChatTurn:
  106. """Named boundary for artifacts, validation and response metadata."""
  107. return turn
  108. _DURABLE_MEMORY_CUE = re.compile(
  109. r"(?:以后|今后|从今往后|长期|一直|每周|每星期|周[一二三四五六日天]|"
  110. r"不喜欢|喜欢|讨厌|避免|不要|不做|不练|我有|我是|慢性|骨盆(?:前|后)倾|"
  111. r"下交叉|臀肌无力|髂腰肌|核心无力|腘绳肌|竖脊肌|腰肌劳损|体态矫正|久坐)"
  112. )
  113. def format_cross_session_memories(memories: list[dict] | None) -> str:
  114. return _format_cross_session_memories(
  115. memories, resolve_facts_fn=resolve_confirmed_memory_facts
  116. )
  117. def youtube_channels_to_avoid(
  118. memories: list[dict] | None, current_message: str = ""
  119. ) -> list[str]:
  120. return _youtube_channels_to_avoid(
  121. memories,
  122. current_message,
  123. resolve_facts_fn=resolve_confirmed_memory_facts,
  124. )
  125. def confirmed_memory_profile(memories: list[dict] | None) -> str:
  126. return _confirmed_memory_profile(
  127. memories, resolve_facts_fn=resolve_confirmed_memory_facts
  128. )
  129. def confirmed_weekly_schedule(memories: list[dict] | None) -> dict[str, str]:
  130. return _confirmed_weekly_schedule(
  131. memories,
  132. resolve_facts_fn=resolve_confirmed_memory_facts,
  133. parse_schedule_fn=parse_weekly_schedule,
  134. )
  135. def active_temporary_health_facts(
  136. memories: list[dict] | None,
  137. ) -> list[dict[str, object]]:
  138. return _active_temporary_health_facts(
  139. memories, resolve_facts_fn=resolve_confirmed_memory_facts
  140. )
  141. def format_response(response: object) -> str:
  142. if isinstance(response, str):
  143. return response
  144. if isinstance(response, dict):
  145. return json.dumps(response, ensure_ascii=False, indent=2)
  146. return str(response)
  147. def resolve_plan_context(
  148. message: str,
  149. profile: dict[str, object],
  150. memories: list[dict] | None,
  151. recovery: MuscleRecoverySnapshot | None = None,
  152. routed_intent: dict[str, object] | None = None,
  153. soreness_reports: list[object] | None = None,
  154. ) -> dict[str, object]:
  155. return _resolve_plan_context(
  156. message=message,
  157. profile=profile,
  158. memories=memories,
  159. recovery=recovery,
  160. routed_intent=routed_intent,
  161. soreness_reports=soreness_reports,
  162. current_instruction_override_fn=current_instruction_override,
  163. is_safety_bypass_request_fn=_is_safety_bypass_request,
  164. recovery_context_payload_fn=_recovery_context_payload,
  165. subject_recovery_regions_fn=_subject_recovery_regions,
  166. explicitly_requested_recovery_regions_fn=explicitly_requested_recovery_regions,
  167. scheduled_weekly_entry_for_message_fn=scheduled_weekly_entry_for_message,
  168. )
  169. def daily_schedule_constraint(message: str, memories: list[dict] | None) -> str:
  170. return _daily_schedule_constraint(
  171. message,
  172. memories,
  173. current_instruction_override_fn=current_instruction_override,
  174. scheduled_weekly_entry_for_message_fn=scheduled_weekly_entry_for_message,
  175. )
  176. def _plan_muscle_resolver(name: str) -> list:
  177. return resolve_muscles_for_exercise(
  178. name,
  179. allow_external_models=deps.external_model_settings_store.get()["external_models_enabled"],
  180. )
  181. def build_agent_input(
  182. message: str,
  183. profile: dict[str, object],
  184. history: list[dict] = None,
  185. memories: list[dict] | None = None,
  186. risk: RiskFinding | None = None,
  187. plan_context: dict[str, object] | None = None,
  188. ) -> str:
  189. current_time = __import__("datetime").datetime.now(__import__("zoneinfo").ZoneInfo("Asia/Shanghai"))
  190. current_time_context = (
  191. "[Current time]\n"
  192. + f"Current date: {current_time.date().isoformat()}\n"
  193. + f"Current time: {current_time.isoformat(timespec='seconds')} (Asia/Shanghai)\n"
  194. + "Resolve today/now/this week from this anchor unless the user explicitly provides a date.\n\n"
  195. )
  196. history_str = ""
  197. if history:
  198. history_str = "【近期对话上下文】\n"
  199. for msg in history:
  200. role = "用户" if msg.get("role") == "user" else "助手"
  201. text = msg.get("text", "")
  202. history_str += f"{role}:{text}\n"
  203. history_str += "\n"
  204. goal = str(profile.get("goal") or "未设置").strip() or "未设置"
  205. plan_context = dict(plan_context or resolve_plan_context(message, profile, memories))
  206. plan_context["goal"] = goal
  207. result = (
  208. # 健康风险提示放在最前:它的优先级高于主目标、周计划和任何偏好,
  209. # 位置靠前也能降低被后续上下文冲淡的概率。
  210. f"{current_time_context}"
  211. f"{risk_directive(risk) if risk is not None else ''}"
  212. "【用户档案(稳定事实)】\n"
  213. f"{profile_summary(profile)}\n\n"
  214. # 优先级说明只此一段:原先这里另有一段【训练设计优先级】,与
  215. # format_plan_context 的一行版、以及从未被调用的 training_priority_context
  216. # 三处并存(BUG-03/BUG-04)。现在全部合并进 format_plan_context。
  217. f"{format_plan_context(plan_context)}"
  218. f"{daily_schedule_constraint(message, memories) if plan_context.get('decision') == 'follow_schedule' else ''}"
  219. f"{format_cross_session_memories(memories)}"
  220. f"{history_str}"
  221. f"【最新用户消息】:{message}"
  222. )
  223. if len(result) > AGENT_INPUT_MAX_CHARS:
  224. raise ContextInputError(
  225. "CONTEXT_BUDGET_EXCEEDED",
  226. "整理后的上下文仍然过长,请缩短当前消息或训练计划。",
  227. status_code=413,
  228. )
  229. return result
  230. def _current_recovery_snapshot(garmin_recovery_hours: float) -> MuscleRecoverySnapshot:
  231. now = datetime.now(ZoneInfo("Asia/Shanghai"))
  232. deps.soreness_store.cleanup_expired(now=now)
  233. return build_recovery_snapshot(
  234. deps.daily_record_store.list_records(),
  235. now=now,
  236. soreness=deps.soreness_store.list_reports(active_only=True, now=now),
  237. garmin_recovery_hours=garmin_recovery_hours,
  238. lookback_days=7,
  239. allow_external_models=deps.external_model_settings_store.get()["external_models_enabled"],
  240. )
  241. def _soreness_report_payload(report: object) -> dict[str, object]:
  242. now = datetime.now(ZoneInfo("Asia/Shanghai"))
  243. return {
  244. "id": report.id,
  245. "region": report.region,
  246. "muscle_ids": list(report.muscle_ids),
  247. "level": report.level,
  248. "reported_at": report.reported_at.isoformat(),
  249. "expires_at": report.expires_at.isoformat(),
  250. "evidence": report.evidence,
  251. "expired": bool(getattr(report, "expired", False)) or report.expires_at <= now,
  252. }
  253. def _soreness_acknowledgement(reports: list[object]) -> str:
  254. labels = {
  255. "recovered": "已恢复",
  256. "sore": "酸痛,将相应减量",
  257. "painful": "疼痛,已升级为安全信号",
  258. }
  259. details = [f"{report.region}{labels.get(report.level, report.level)}" for report in reports]
  260. return "已记录:" + ";".join(details) + "。记录将在 72 小时后自动过期,可在数据管理中修改或删除。"
  261. def _is_only_soreness_feedback(message: str) -> bool:
  262. normalized = re.sub(r"\s+", "", str(message or ""))
  263. stripped = normalized
  264. from fithealth_agent.muscle_recovery import REGION_ALIASES
  265. for aliases in REGION_ALIASES.values():
  266. for alias in aliases:
  267. stripped = stripped.replace(alias, "")
  268. stripped = re.sub(r"(?:有点|一点|稍微|轻微|很|非常|比较|还|又|酸痛|酸|疼痛|疼|痛|不酸|不疼|不痛|正常|好了|恢复了)", "", stripped)
  269. if re.search(r"怎么办|怎么处理|如何|建议|要不要|需要吗|能不能|可以吗", normalized):
  270. return False
  271. if len(re.sub(r"[,。!?、;;::吗呢吧呀\?]", "", stripped)) < 4:
  272. return True
  273. return not bool(re.search(
  274. r"(?:训练计划|帮我|怎么练|如何练|能不能练|可以练|继续练|照常练|就要练|坚持练|"
  275. r"安排|推荐动作|生成计划|查看|查询|保存|修改|删除|怎么办|如何处理|建议|本周|这周)",
  276. re.sub(r"\s+", "", message),
  277. ))
  278. def _immediate_memory_candidate(message: str, *, allow_external_models: bool) -> dict[str, object] | None:
  279. """Persist explicit durable facts as a pending candidate during chat.
  280. Logout remains a compatibility sweep, but durable facts must not depend on a
  281. browser close event. This path intentionally uses the same information
  282. router and InfoStore normalisation as logout; it never auto-confirms facts.
  283. """
  284. if not allow_external_models or not _DURABLE_MEMORY_CUE.search(str(message or "")):
  285. return None
  286. decision = deps.route_information(
  287. [{"role": "user", "text": str(message)}],
  288. allow_external_models=True,
  289. )
  290. if not decision.get("save"):
  291. return None
  292. facts = [
  293. fact
  294. for fact in normalize_memory_facts(decision.get("facts"))
  295. if fact_retention_class(fact) in {"long_term", "medium"}
  296. ]
  297. if not facts:
  298. return None
  299. # Retries and later logout sweeps must not create another pending card for
  300. # the same active fact. Different weekly schedules remain distinct here;
  301. # version conflict handling still applies when the user confirms them.
  302. deps.info_store.cleanup_expired()
  303. existing = {
  304. (str(fact.get("namespace")), str(fact.get("key")), str(fact.get("value")).casefold())
  305. for memory in deps.info_store.get_all()
  306. if isinstance(memory, dict)
  307. for fact in normalize_memory_facts(memory.get("facts"))
  308. if fact.get("status") in {"active", "rejected"} and fact_is_active(fact)
  309. }
  310. new_facts = [
  311. fact for fact in facts
  312. if (str(fact.get("namespace")), str(fact.get("key")), str(fact.get("value")).casefold())
  313. not in existing
  314. ]
  315. if not new_facts:
  316. return None
  317. memory_type = str(decision.get("type") or "training_feedback")
  318. entry = deps.info_store.add_entry(
  319. summary=str(decision.get("summary") or "")[:200],
  320. metadata={
  321. "reason": decision.get("reason", ""),
  322. "pipeline_stage": decision.get("pipeline_stage", "level3"),
  323. "capture": "chat_turn",
  324. },
  325. expires_at=None,
  326. memory_type=memory_type,
  327. importance=int(decision.get("importance", 1)),
  328. user_confirmed=False,
  329. facts=new_facts,
  330. )
  331. return {
  332. "entry_id": entry["id"],
  333. "summary": entry["summary"],
  334. "facts": [
  335. {"namespace": fact["namespace"], "key": fact["key"], "value": fact["value"]}
  336. for fact in entry["facts"]
  337. ],
  338. }
  339. def _date_range_memory_candidate(constraint: dict[str, object]) -> dict[str, object] | None:
  340. if constraint.get("scope") != "date_range":
  341. return None
  342. fact = normalize_memory_facts([{
  343. "namespace": "health",
  344. "key": "injury_or_constraint",
  345. "status": "active",
  346. "evidence": str(constraint.get("value") or "")[:160],
  347. **constraint,
  348. }])
  349. if not fact:
  350. return None
  351. target = fact[0]
  352. identity = (target["namespace"], target["key"], str(target["value"]).casefold())
  353. for memory in deps.info_store.get_all():
  354. for existing in normalize_memory_facts(memory.get("facts") if isinstance(memory, dict) else None):
  355. if (
  356. existing.get("status") in {"active", "rejected"}
  357. and fact_is_active(existing)
  358. and (existing.get("namespace"), existing.get("key"), str(existing.get("value")).casefold()) == identity
  359. ):
  360. return None
  361. entry = deps.info_store.add_entry(
  362. summary=f"临时训练限制:{target['value']}",
  363. metadata={"capture": "chat_date_range"},
  364. expires_at=None,
  365. memory_type="constraint",
  366. importance=5,
  367. user_confirmed=False,
  368. facts=fact,
  369. )
  370. return {
  371. "entry_id": entry["id"],
  372. "summary": entry["summary"],
  373. "facts": [{
  374. "namespace": target["namespace"], "key": target["key"], "value": target["value"],
  375. "scope": target["scope"], "valid_from": target.get("valid_from"),
  376. "valid_until": target.get("valid_until"),
  377. }],
  378. }
  379. def _acute_injury_memory_candidate(message: str, finding: RiskFinding) -> dict[str, object] | None:
  380. """Record an urgent, user-stated injury as a short-lived pending fact.
  381. This is deliberately local and deterministic. An acute safety statement
  382. must survive an LLM timeout, but remains unconfirmed and expires under the
  383. existing recovery-status TTL unless the user confirms it.
  384. """
  385. if finding.level != "urgent":
  386. return None
  387. from fithealth_agent.muscle_recovery import REGION_ALIASES
  388. regions = [
  389. region for region, aliases in REGION_ALIASES.items()
  390. if any(alias in str(message or "") for alias in aliases)
  391. ]
  392. concise_value = "、".join(dict.fromkeys(regions)) + (":" if regions else "") + finding.summary
  393. fact = normalize_memory_facts([{
  394. "namespace": "health",
  395. "key": "recovery_status",
  396. "value": concise_value[:120],
  397. "status": "active",
  398. "evidence": str(message or "").strip()[:160],
  399. }])
  400. if not fact:
  401. return None
  402. deps.info_store.cleanup_expired()
  403. candidate_fact = fact[0]
  404. identity = (
  405. str(candidate_fact["namespace"]),
  406. str(candidate_fact["key"]),
  407. str(candidate_fact["value"]).casefold(),
  408. )
  409. for memory in deps.info_store.get_all():
  410. if not isinstance(memory, dict):
  411. continue
  412. for existing in normalize_memory_facts(memory.get("facts")):
  413. existing_identity = (
  414. str(existing.get("namespace")), str(existing.get("key")),
  415. str(existing.get("value")).casefold(),
  416. )
  417. if existing.get("status") in {"active", "rejected"} and fact_is_active(existing) and existing_identity == identity:
  418. return None
  419. entry = deps.info_store.add_entry(
  420. summary=f"用户报告急性伤病信号:{finding.summary}",
  421. metadata={"capture": "chat_safety", "risk_level": finding.level, "risk_labels": list(finding.labels)},
  422. expires_at=None,
  423. memory_type="training_feedback",
  424. importance=5,
  425. user_confirmed=False,
  426. facts=fact,
  427. )
  428. return {
  429. "entry_id": entry["id"],
  430. "summary": entry["summary"],
  431. "facts": [{"namespace": "health", "key": "recovery_status", "value": candidate_fact["value"]}],
  432. }
  433. async def chat(payload: dict[str, object]) -> ChatResult:
  434. turn = stage_request_context(ChatTurn.from_payload(payload))
  435. turn = stage_health_safety(turn)
  436. turn = stage_intent_routing(turn)
  437. turn = stage_local_navigation(turn)
  438. turn = stage_plan_context(turn)
  439. turn = stage_postprocess(turn)
  440. payload = turn.payload
  441. message = turn.message
  442. history = turn.history
  443. profile = turn.profile
  444. source = turn.source
  445. plan_context = payload["plan_context"]
  446. garmin_recovery_hours = payload["garmin_recovery_hours"]
  447. external_models_enabled = bool(turn.debug["external_models_enabled"])
  448. asked_regions = payload["soreness_prompt_regions"]
  449. pending_memory_entry_ids = payload["pending_memory_entry_ids"]
  450. saved_soreness: list[object] = []
  451. soreness_ack = ""
  452. memory_candidates: list[dict[str, object]] = []
  453. def _chat_response(
  454. reply: str,
  455. *,
  456. artifact: dict[str, object] | None = None,
  457. source: str | None = None,
  458. status_code: int = 200,
  459. include_soreness_ack: bool = True,
  460. **extra: object,
  461. ) -> ChatResult:
  462. final_reply = str(reply or "")
  463. if include_soreness_ack and soreness_ack:
  464. final_reply = soreness_ack + ("\n\n" + final_reply if final_reply else "")
  465. if memory_candidates:
  466. candidate_labels = [
  467. str(candidate.get("summary") or "检测到一条长期偏好或限制")
  468. for candidate in memory_candidates
  469. ]
  470. final_reply += (
  471. ("\n\n" if final_reply else "")
  472. + "检测到待确认的跨会话记忆:"
  473. + ";".join(candidate_labels)
  474. + "。要加入跨会话记忆吗?"
  475. )
  476. body: dict[str, object] = {
  477. **extra,
  478. "reply": final_reply,
  479. "artifact": artifact,
  480. "soreness_saved": bool(saved_soreness),
  481. "soreness_reports": [
  482. _soreness_report_payload(item) for item in saved_soreness
  483. ],
  484. "asked_regions": asked_regions,
  485. }
  486. if source is not None:
  487. body["source"] = source
  488. if memory_candidates:
  489. body["memory_candidate"] = memory_candidates[0]
  490. body["memory_candidates"] = list(memory_candidates)
  491. return ChatResult(body=body, status_code=status_code)
  492. confirmation_decision = _memory_confirmation_decision(message)
  493. if pending_memory_entry_ids and confirmation_decision is not None:
  494. changed = 0
  495. try:
  496. for entry_id in pending_memory_entry_ids:
  497. result = (
  498. deps.info_store.confirm_entry(entry_id)
  499. if confirmation_decision
  500. else deps.info_store.reject_entry(entry_id)
  501. )
  502. if result is not None:
  503. changed += 1
  504. except ValueError as exc:
  505. return _chat_response(
  506. f"记忆确认失败:{exc}", source="memory_confirmation", status_code=409
  507. )
  508. if not changed:
  509. return _chat_response(
  510. "这些待确认记忆已不存在或已经处理。", source="memory_confirmation", status_code=404
  511. )
  512. return _chat_response(
  513. f"已{'加入' if confirmation_decision else '拒绝'} {changed} 条跨会话记忆。",
  514. source="memory_confirmation",
  515. memory_confirmation={"accepted": confirmation_decision, "count": changed},
  516. )
  517. user_health_statement = None
  518. if source == "chat":
  519. user_health_statement = await run_in_threadpool(deps.classify_user_health_statement, message)
  520. immediate_memory_candidate: dict[str, object] | None = None
  521. health_risk = None
  522. if source == "chat" and user_health_statement is not False:
  523. health_risk = screen_health_risk(message)
  524. recovery_snapshot = _current_recovery_snapshot(garmin_recovery_hours)
  525. temporary_constraint = temporary_constraint_for_message(message) if source == "chat" else None
  526. if temporary_constraint is not None and temporary_constraint.get("scope") == "date_range":
  527. try:
  528. date_range_candidate = _date_range_memory_candidate(temporary_constraint)
  529. if date_range_candidate is not None:
  530. memory_candidates.append(date_range_candidate)
  531. except (MemoryStoreDegradedError, OSError, ValueError):
  532. logger.exception("日期区间限制候选保存失败")
  533. soreness_reports = (
  534. deps.parse_soreness_reply(message, asked_regions)
  535. if source == "chat" and (bool(asked_regions) or user_health_statement is not False)
  536. else []
  537. )
  538. if (
  539. source == "chat"
  540. and not soreness_reports
  541. and not (health_risk is not None and health_risk.level in {"urgent", "emergency"})
  542. and soreness_reply_needs_clarification(message, asked_regions)
  543. ):
  544. return _chat_response(
  545. "你说了当前感受,但我刚才询问了多个部位。请明确是哪一个区域,例如“手臂有点酸”或“腿部正常”。",
  546. source="soreness_clarification",
  547. )
  548. if soreness_reports:
  549. try:
  550. saved_soreness = list(deps.soreness_store.add_reports(soreness_reports))
  551. except (OSError, ValueError) as exc:
  552. logger.exception("肌群酸痛反馈保存失败")
  553. return _chat_response(f"酸痛反馈未能保存:{exc}", status_code=503)
  554. soreness_ack = _soreness_acknowledgement(saved_soreness)
  555. recovery_snapshot = _current_recovery_snapshot(garmin_recovery_hours)
  556. active_soreness_reports = deps.soreness_store.list_reports(active_only=True)
  557. # AGENT-01:确定性健康风险筛查。
  558. # 放在意图路由之前有三个原因:(1) 急症不该等一次外部模型往返;
  559. # (2) 关闭联网模型或网络故障时同样要生效;(3) 这条判断不依赖任何
  560. # 已确认记忆——用户在**当前这条消息**里新出现的症状本来就不在记忆里。
  561. # 只筛查对话消息;上传的训练计划正文里出现症状词不算用户主诉。
  562. painful_regions = [report.region for report in soreness_reports if report.level == "painful"]
  563. if painful_regions:
  564. health_risk = merge_findings(health_risk, acute_pain_finding(painful_regions))
  565. if source == "chat" and health_risk is not None and health_risk.level == "urgent":
  566. try:
  567. acute_candidate = _acute_injury_memory_candidate(message, health_risk)
  568. if acute_candidate is not None:
  569. memory_candidates.append(acute_candidate)
  570. except (MemoryStoreDegradedError, OSError, ValueError):
  571. logger.exception("急性伤病候选保存失败")
  572. if health_risk is not None and health_risk.level == "emergency":
  573. # Emergency guidance stays visually undiluted. The structured flag still
  574. # tells the client that any soreness report from this turn was saved.
  575. return _chat_response(
  576. emergency_reply(health_risk),
  577. source="health_risk_block",
  578. include_soreness_ack=False,
  579. health_risk={"level": health_risk.level, "signals": list(health_risk.labels)},
  580. workflow_state=str(PlanWorkflowState.CONSTRAINT_CONFLICT),
  581. )
  582. if source == "chat" and (health_risk is None or health_risk.level in {CAUTION, URGENT}):
  583. try:
  584. durable_candidate = await run_in_threadpool(
  585. _immediate_memory_candidate,
  586. message,
  587. allow_external_models=external_models_enabled,
  588. )
  589. if durable_candidate is not None:
  590. memory_candidates.append(durable_candidate)
  591. except (MemoryStoreDegradedError, OSError, ValueError):
  592. logger.exception("即时长期记忆候选保存失败")
  593. immediate_memory_candidate = memory_candidates[0] if memory_candidates else None
  594. if soreness_reports and _is_only_soreness_feedback(message):
  595. deps.info_store.cleanup_expired()
  596. memories = deps.info_store.get_context_memories(n=5)
  597. resolved_plan_context = resolve_plan_context(
  598. message, profile, memories, recovery=recovery_snapshot,
  599. soreness_reports=active_soreness_reports,
  600. )
  601. reply = ""
  602. if painful_regions and health_risk is not None:
  603. reply = urgent_plan_block_note(health_risk)
  604. return _chat_response(
  605. reply,
  606. source="local_soreness_feedback",
  607. plan_context=resolved_plan_context,
  608. health_risk=(
  609. {"level": health_risk.level, "signals": list(health_risk.labels)}
  610. if health_risk is not None else None
  611. ),
  612. workflow_state=resolved_plan_context["workflow_state"],
  613. **({"memory_candidate": immediate_memory_candidate} if immediate_memory_candidate else {}),
  614. **({"memory_candidates": memory_candidates} if memory_candidates else {}),
  615. )
  616. if source == "uploaded_plan":
  617. updates, updated_fields = {}, []
  618. chat_intent = None
  619. else:
  620. chat_intent = await run_in_threadpool(
  621. deps.route_chat_intent,
  622. message,
  623. allow_external_models=external_models_enabled,
  624. )
  625. updates, updated_fields = validate_profile_tool_updates(
  626. chat_intent.profile_updates, message
  627. )
  628. profile_update_artifact = (
  629. {
  630. "type": "profile_update",
  631. "updates": updates,
  632. "fields": updated_fields,
  633. **(
  634. {"equipment_diff": equipment_change_preview(profile, updates)}
  635. if equipment_change_preview(profile, updates) is not None else {}
  636. ),
  637. }
  638. if updates
  639. else None
  640. )
  641. pending_view_artifact: dict[str, object] | None = None
  642. pending_reply_prefix = ""
  643. pending_view_source: str | None = None
  644. # BUG-02:外部意图路由不可用时(关闭联网模型、缺 API key、超时、网络抖动),
  645. # route_chat_intent 会返回一个所有位都为 False 的空 ChatIntent,于是
  646. # "查看训练记录"这类**纯本地读操作**一路掉到下面的 503——而欢迎语里
  647. # 明明写着可以这么输入。这里用已有的确定性规则兜底,让本地能力在离线
  648. # 状态下同样可用。
  649. wants_training_records = (
  650. chat_intent is not None and chat_intent.view_training_records
  651. ) or (source == "chat" and is_training_record_query(message))
  652. if wants_training_records:
  653. records = _training_record_items(deps.daily_record_store.list_records())
  654. default_date = (
  655. (chat_intent.training_records_date if chat_intent is not None else "")
  656. or _requested_record_date(message)
  657. or (
  658. records[0]["date"]
  659. if records
  660. else datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
  661. )
  662. )
  663. navigation_only = navigation_only_message(message)
  664. pending_view_artifact = {
  665. "type": "training_records",
  666. "default_date": default_date,
  667. }
  668. pending_reply_prefix = "已打开本地训练记录。选择日期后,可在右侧下拉框查看当天的每一条训练。"
  669. pending_view_source = "local_training_records"
  670. if navigation_only or not external_models_enabled:
  671. offline_note = (
  672. "\n\n外部模型当前已关闭,因此暂时无法继续回答同一条消息中的其他问题。"
  673. if not navigation_only and not external_models_enabled else ""
  674. )
  675. return _chat_response(
  676. pending_reply_prefix + offline_note,
  677. artifact=pending_view_artifact,
  678. source=pending_view_source,
  679. )
  680. wants_nutrition_records = (
  681. chat_intent is not None and chat_intent.view_nutrition_records
  682. ) or (
  683. source == "chat"
  684. and any(word in message for word in ("查看饮食", "查看营养", "营养数据", "饮食数据", "摄入数据"))
  685. )
  686. if wants_nutrition_records:
  687. default_date = (
  688. (chat_intent.nutrition_records_date if chat_intent is not None else "")
  689. or _nutrition_record_date(message)
  690. or datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
  691. )
  692. navigation_only = navigation_only_message(message)
  693. pending_view_artifact = pending_view_artifact or {
  694. "type": "nutrition_records",
  695. "default_date": default_date,
  696. }
  697. nutrition_prefix = "已打开本地营养记录。选择日期后,可在右侧下拉框查看当天的不同饮食组。"
  698. pending_reply_prefix = "\n\n".join(filter(None, (pending_reply_prefix, nutrition_prefix)))
  699. pending_view_source = pending_view_source or "local_nutrition_records"
  700. if navigation_only or not external_models_enabled:
  701. offline_note = (
  702. "\n\n外部模型当前已关闭,因此暂时无法继续回答同一条消息中的其他问题。"
  703. if not navigation_only and not external_models_enabled else ""
  704. )
  705. return _chat_response(
  706. pending_reply_prefix + offline_note,
  707. artifact=pending_view_artifact,
  708. source=pending_view_source,
  709. )
  710. if chat_intent is not None and chat_intent.save_existing_training_plan:
  711. # BUG-05:优先用服务端缓存的完整正文。回捞聊天历史只作为进程重启
  712. # 后的兜底——history 已被上下文预算截断过,可能是残片。
  713. # 用 find() 而不是 latest():一个会话里可能生成过多份计划,用户说
  714. # "保存那份腿的计划"时无条件取最后一份会静默存错。
  715. draft = deps.plan_draft_cache.find(
  716. subject=chat_intent.saved_plan_subject or "",
  717. suggested_date=chat_intent.saved_plan_date or "",
  718. )
  719. content = draft.content if draft is not None else most_recent_complete_training_plan(history)
  720. if not content:
  721. return _chat_response(
  722. "没有找到可保存的完整训练计划。\n\n"
  723. "可能的原因:还没有生成过计划;或者页面刷新过、服务重启过,"
  724. "导致上一份计划的正文已经不在。请让我重新生成一份,"
  725. "再点击计划下方的“保存计划”。",
  726. source="local_plan_save",
  727. status_code=400,
  728. )
  729. subject = (
  730. (draft.subject if draft is not None else "")
  731. or chat_intent.saved_plan_subject
  732. or extract_plan_subject(content)
  733. )
  734. title = plan_card_title(
  735. (draft.title if draft is not None else "")
  736. or infer_plan_title(content, subject),
  737. subject,
  738. )
  739. plan_date = (
  740. chat_intent.saved_plan_date
  741. or (draft.suggested_date if draft is not None else "")
  742. or datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
  743. )
  744. deps.info_store.cleanup_expired()
  745. memories = deps.info_store.get_context_memories(n=5)
  746. expected_subject = subject
  747. try:
  748. saved_day = date.fromisoformat(plan_date)
  749. scheduled_entry = confirmed_weekly_schedule_entry(deps.info_store.get_all(), saved_day)
  750. if (
  751. (not subject or is_generic_training_subject(subject))
  752. and scheduled_entry is not None
  753. and scheduled_entry.get("type") != "rest"
  754. ):
  755. expected_subject = str(scheduled_entry.get("subject") or subject)
  756. except ValueError:
  757. pass
  758. safety_constraints = [
  759. str(fact.get("value") or "")
  760. for fact in resolve_confirmed_memory_facts(memories)
  761. if fact.get("status", "active") == "active"
  762. and fact.get("user_confirmed", True)
  763. and fact.get("namespace") == "health"
  764. and fact.get("key") in {"injury_or_constraint", "recovery_status"}
  765. ]
  766. plan_validation = validate_generated_training_plan(
  767. content,
  768. memories,
  769. expected_subject,
  770. recovery=recovery_snapshot,
  771. safety_constraints=safety_constraints,
  772. resolver=_plan_muscle_resolver,
  773. check_subject=False,
  774. )
  775. saved_goal_alignment = await run_in_threadpool(
  776. deps.validate_plan_goal_alignment,
  777. content,
  778. user_request=message,
  779. fallback_subject=expected_subject,
  780. weekly_subject=(
  781. str(scheduled_entry.get("subject") or "")
  782. if "scheduled_entry" in locals() and scheduled_entry is not None
  783. else ""
  784. ),
  785. schedule_decision="override_today" if subject and not is_generic_training_subject(subject) else "follow_schedule",
  786. allow_external_models=external_models_enabled,
  787. )
  788. if not saved_goal_alignment.get("passed"):
  789. missing = "、".join(saved_goal_alignment.get("missing_subjects") or [expected_subject])
  790. plan_validation.append(f"计划未覆盖用户要求的训练目标:{missing}")
  791. if plan_validation:
  792. return _chat_response(
  793. "该训练计划未通过已确认记忆的后端校验,因此不能保存。\n\n## 计划校验未通过\n"
  794. + "\n".join(f"- {item}" for item in plan_validation)
  795. + "\n请先修正以上问题,再保存训练计划。"
  796. "\n\n你还问了另一件事;处理完这项安全冲突后,我再继续回答。",
  797. source="local_plan_save",
  798. status_code=409,
  799. plan_validation={"passed": False, "violations": plan_validation},
  800. )
  801. return _chat_response(
  802. "已找到本次会话中最近生成的完整训练计划,请确认下方信息后保存。",
  803. artifact={
  804. "type": "training_plan",
  805. "subject": subject,
  806. "title": title,
  807. "content": content,
  808. "source": "agent_generated",
  809. "suggested_date": plan_date,
  810. # 带上 draft_id,让后续 /plans 也走"按 id 取服务端原文"这条路,
  811. # 而不是退回靠前端传值——否则这条路径只是碰巧内容完整才没出错。
  812. **({"draft_id": draft.id} if draft is not None else {}),
  813. },
  814. source="local_plan_save",
  815. )
  816. if (chat_intent is not None and chat_intent.view_profile) or (
  817. source == "chat" and is_profile_query(message)
  818. ):
  819. deps.info_store.cleanup_expired()
  820. navigation_only = navigation_only_message(message)
  821. profile_prefix = (
  822. "## 个人档案\n"
  823. + profile_summary(profile, include_birth_date=False)
  824. + "\n\n## 跨会话记忆\n"
  825. + confirmed_memory_profile(deps.info_store.get_all())
  826. + "\n\n待确认记忆不会用于后续对话;可在“数据管理 → 临时记忆”中查看、确认或删除。"
  827. )
  828. pending_reply_prefix = "\n\n".join(filter(None, (pending_reply_prefix, profile_prefix)))
  829. pending_view_source = pending_view_source or "local_profile"
  830. if navigation_only or not external_models_enabled:
  831. offline_note = (
  832. "\n\n外部模型当前已关闭,因此暂时无法继续回答同一条消息中的其他问题。"
  833. if not navigation_only and not external_models_enabled else ""
  834. )
  835. return _chat_response(
  836. pending_reply_prefix + offline_note,
  837. artifact=pending_view_artifact,
  838. source=pending_view_source,
  839. )
  840. projected = merge_profile_updates_with_existing(profile, updates) if updates else profile
  841. is_complete = deps.profile_store.is_complete(projected)
  842. if not is_complete:
  843. missing = deps.profile_store.missing_fields(projected)
  844. return _chat_response(
  845. onboarding_reply(projected, missing, updated_fields)
  846. + "\n\n你还问了另一件事;补完档案后,我再继续回答。",
  847. artifact=profile_update_artifact,
  848. source="onboarding",
  849. )
  850. if updated_fields:
  851. return _chat_response(
  852. "\u7528\u6237\u4fe1\u606f\u5df2\u5b8c\u5584\uff0c\u8bf7\u786e\u8ba4\u4e0b\u65b9\u53d8\u66f4\u540e\u7ee7\u7eed\u3002\n\n"
  853. + profile_summary(projected, include_birth_date=False),
  854. artifact=profile_update_artifact,
  855. source="profile_update",
  856. )
  857. try:
  858. weekly_reply = deps.build_current_week_reply(
  859. message,
  860. health_store=deps.health_store,
  861. daily_record_store=deps.daily_record_store,
  862. profile=profile,
  863. today=datetime.now(ZoneInfo("Asia/Shanghai")).date(),
  864. recovery=recovery_snapshot,
  865. soreness_reports=active_soreness_reports,
  866. )
  867. except (OSError, ValueError, sqlite3.Error):
  868. logger.exception("本周数据本地查询失败")
  869. return _chat_response("本周数据读取失败,请检查已导入数据是否完整。", status_code=500)
  870. if weekly_reply is not None:
  871. return _chat_response(weekly_reply, source="local_weekly_summary")
  872. if not external_models_enabled:
  873. # BUG-02:以前这里只丢一句"外部模型已关闭",用户不知道离线到底还能做什么。
  874. # 上面的本地分支(训练记录 / 个人档案 / 本周汇总)已经先行拦截,能走到
  875. # 这里说明确实需要模型;给出可直接照抄的本地指令,比空泛一句有用得多。
  876. local_commands = "「查看训练记录」「查看个人信息」「查看本周数据」"
  877. hint = (
  878. f"这类问题需要模型参与。不过你可以直接输入 {local_commands} 来查看已保存的本地数据;"
  879. "健康数据的导入、训练组编辑、备份与删除也都不受影响。"
  880. if is_training_related(message)
  881. else f"你仍可使用本地功能:输入 {local_commands},以及健康数据导入、训练编辑、备份和删除。"
  882. )
  883. return _chat_response(
  884. "外部模型已关闭,因此不会发送你的对话、档案或记忆。" + hint,
  885. source="external_models_disabled",
  886. status_code=503,
  887. )
  888. try:
  889. deps.info_store.cleanup_expired()
  890. memory_intent = (
  891. "create_training_plan"
  892. if chat_intent is not None and chat_intent.create_training_plan
  893. else "search_youtube_video" if "youtube" in message.casefold() or "视频" in message else ""
  894. )
  895. memories = deps.info_store.get_context_memories(n=5, intent=memory_intent)
  896. candidate_memories = deps.info_store.get_enforceable_memories() if hasattr(deps.info_store, "get_enforceable_memories") else None
  897. enforceable_memories = candidate_memories if isinstance(candidate_memories, list) else memories
  898. routed_plan_intent = (
  899. {
  900. "schedule_decision": chat_intent.schedule_decision,
  901. "subject": chat_intent.training_plan_subject,
  902. "requested_subjects": getattr(chat_intent, "requested_subjects", []),
  903. "temporary_health_constraints": list(dict.fromkeys(
  904. chat_intent.temporary_health_constraints
  905. + ([str(temporary_constraint["value"])] if temporary_constraint else [])
  906. )),
  907. "excluded_subjects": chat_intent.excluded_subjects,
  908. "needs_clarification": chat_intent.needs_clarification,
  909. }
  910. if chat_intent is not None and chat_intent.create_training_plan
  911. else None
  912. )
  913. resolved_plan_context = resolve_plan_context(
  914. message,
  915. profile,
  916. enforceable_memories,
  917. recovery=recovery_snapshot,
  918. routed_intent=routed_plan_intent,
  919. soreness_reports=active_soreness_reports,
  920. )
  921. scheduled_plan = (
  922. scheduled_plan_for_message(message, deps.info_store.get_all())
  923. if resolved_plan_context.get("decision") == "follow_schedule"
  924. else None
  925. )
  926. if scheduled_plan is not None:
  927. scheduled_date, scheduled_subject = scheduled_plan
  928. resolved_plan_context.update({
  929. "scheduled_subject": scheduled_subject,
  930. "scheduled_date": scheduled_date.isoformat(),
  931. "effective_subject": scheduled_subject,
  932. })
  933. if (
  934. chat_intent is not None
  935. and chat_intent.create_training_plan
  936. and resolved_plan_context.get("blocking_reasons")
  937. ):
  938. return _chat_response(
  939. "当前请求与已确认的安全限制冲突,不能按原要求生成计划。"
  940. "请先说明是否要修改或清除该安全限制。\n\n"
  941. "当前生效的限制:"
  942. + ";".join(resolved_plan_context.get("active_safety_constraints") or ["(未列出)"])
  943. + "\n\n你还问了另一件事;处理完这项安全冲突后,我再继续回答。",
  944. source="plan_context_safety_block",
  945. status_code=409,
  946. plan_context=resolved_plan_context,
  947. workflow_state=str(PlanWorkflowState.CONSTRAINT_CONFLICT),
  948. )
  949. if (
  950. chat_intent is not None
  951. and chat_intent.create_training_plan
  952. and resolved_plan_context.get("decision") == "rest_today"
  953. ):
  954. scheduled_subject = resolved_plan_context.get("scheduled_subject")
  955. scheduled_note = f",原周计划科目为{scheduled_subject}" if scheduled_subject else ""
  956. rest_reply = "已将本次安排为休息" + scheduled_note + "。今天不生成训练计划;恢复后可再安排下一次训练。"
  957. return _chat_response(
  958. rest_reply,
  959. artifact=profile_update_artifact,
  960. source="plan_context_rest",
  961. plan_context=resolved_plan_context,
  962. workflow_state=str(resolved_plan_context["workflow_state"]),
  963. )
  964. if chat_intent is not None and chat_intent.create_training_plan and resolved_plan_context.get("clarification_required"):
  965. return _chat_response(
  966. "你已表示本次不按周计划训练,但还没有说明是休息还是更换训练科目。请明确选择后,我再生成计划。",
  967. source="plan_context_clarification",
  968. status_code=409,
  969. plan_context=resolved_plan_context,
  970. workflow_state=str(PlanWorkflowState.NEEDS_CLARIFICATION),
  971. )
  972. avoided_youtube_channels = youtube_channels_to_avoid(memories, message)
  973. agent = deps.create_fithealth_agent(
  974. avoid_youtube_channels=avoided_youtube_channels
  975. )
  976. try:
  977. agent_input = build_agent_input(message, profile, history, memories, risk=health_risk, plan_context=resolved_plan_context)
  978. except ContextInputError as exc:
  979. return context_error_response(exc)
  980. answer = format_response(await run_in_threadpool(agent.run, agent_input))
  981. if pending_reply_prefix:
  982. answer = pending_reply_prefix + "\n\n" + answer
  983. artifact = None
  984. if source == "uploaded_plan" and looks_like_complete_training_plan(answer):
  985. subject = extract_plan_subject(answer, str(plan_context.get("subject") or ""))
  986. artifact = {
  987. "type": "training_plan",
  988. "subject": subject,
  989. "title": infer_plan_title(answer, subject),
  990. "content": answer,
  991. "source": "uploaded_optimized",
  992. "suggested_date": str(plan_context.get("suggested_date") or ""),
  993. }
  994. elif (
  995. source == "chat"
  996. and chat_intent is not None
  997. and chat_intent.create_training_plan
  998. and looks_like_complete_training_plan(answer)
  999. ):
  1000. if scheduled_plan is not None:
  1001. scheduled_date, subject = scheduled_plan
  1002. suggested_date = scheduled_date.isoformat()
  1003. else:
  1004. subject = chat_intent.training_plan_subject
  1005. suggested_date = ""
  1006. artifact = {
  1007. "type": "training_plan",
  1008. "subject": subject if subject.endswith(("训练", "计划")) else subject + "训练",
  1009. "title": plan_card_title(chat_intent.training_plan_title, subject),
  1010. "content": answer,
  1011. "source": "agent_generated",
  1012. "suggested_date": suggested_date,
  1013. }
  1014. elif scheduled_plan is not None and looks_like_complete_training_plan(answer):
  1015. scheduled_date, scheduled_subject = scheduled_plan
  1016. artifact = {
  1017. "type": "training_plan",
  1018. "subject": scheduled_subject,
  1019. "title": infer_plan_title(answer, scheduled_subject),
  1020. "content": answer,
  1021. "source": "agent_generated",
  1022. "suggested_date": scheduled_date.isoformat(),
  1023. }
  1024. plan_validation: list[str] = []
  1025. first_plan_validation: list[str] = []
  1026. plan_auto_correction: dict[str, object] = {
  1027. "attempted": False,
  1028. "passed": False,
  1029. "first_violations": [],
  1030. "final_violations": [],
  1031. }
  1032. # AGENT-01(urgent 档):急性损伤信号下确定性地拒绝产出可保存的计划。
  1033. # 放在计划校验之前——无论模型写了什么,后端都不放行这个 artifact。
  1034. if (
  1035. artifact
  1036. and artifact.get("type") == "training_plan"
  1037. and health_risk is not None
  1038. and health_risk.blocks_training_plan()
  1039. ):
  1040. artifact = None
  1041. answer += "\n\n" + urgent_plan_block_note(health_risk)
  1042. if artifact and artifact.get("type") == "training_plan":
  1043. expected_plan_subject = str(
  1044. resolved_plan_context.get("effective_subject")
  1045. or artifact.get("subject")
  1046. or ""
  1047. )
  1048. plan_validation = validate_generated_training_plan(
  1049. answer,
  1050. enforceable_memories,
  1051. expected_plan_subject,
  1052. recovery=recovery_snapshot,
  1053. safety_constraints=list(resolved_plan_context.get("active_safety_constraints") or []),
  1054. explicitly_requested=set((resolved_plan_context.get("muscle_recovery") or {}).get("explicitly_requested") or []),
  1055. resolver=_plan_muscle_resolver,
  1056. check_subject=False,
  1057. )
  1058. goal_alignment = await run_in_threadpool(
  1059. deps.validate_plan_goal_alignment,
  1060. answer,
  1061. user_request=message,
  1062. requested_subjects=(getattr(chat_intent, "requested_subjects", []) if chat_intent is not None else []),
  1063. fallback_subject=expected_plan_subject,
  1064. weekly_subject=str(resolved_plan_context.get("scheduled_subject") or ""),
  1065. schedule_decision=str(resolved_plan_context.get("decision") or "follow_schedule"),
  1066. allow_external_models=external_models_enabled,
  1067. )
  1068. if not goal_alignment.get("passed"):
  1069. missing = "、".join(goal_alignment.get("missing_subjects") or [expected_plan_subject])
  1070. plan_validation.append(f"计划未覆盖用户要求的训练目标:{missing}")
  1071. if plan_validation:
  1072. first_plan_validation = list(plan_validation)
  1073. plan_auto_correction.update({
  1074. "attempted": True,
  1075. "first_violations": first_plan_validation,
  1076. })
  1077. correction_prompt = (
  1078. "你刚才生成的训练计划未通过后端安全校验。请只输出一份完整、可直接使用的修正版训练计划,"
  1079. "不要解释校验过程,也不要遗漏原请求的训练目标。必须逐项消除以下违规:\n"
  1080. + "\n".join(f"- {item}" for item in first_plan_validation)
  1081. + "\n\n原始用户请求:\n" + message[:4000]
  1082. + "\n\n第一次计划:\n" + str(artifact.get("content") or answer)[:24000]
  1083. )
  1084. try:
  1085. correction_agent = deps.create_fithealth_agent(
  1086. avoid_youtube_channels=avoided_youtube_channels
  1087. )
  1088. corrected_answer = format_response(
  1089. await run_in_threadpool(correction_agent.run, correction_prompt)
  1090. )
  1091. except Exception: # noqa: BLE001 - 自动修正失败应降级为明确的校验失败,而非整次 500
  1092. logger.exception("训练计划自动修正调用失败")
  1093. corrected_answer = ""
  1094. corrected_artifact = dict(artifact)
  1095. corrected_artifact["content"] = corrected_answer
  1096. corrected_artifact["source"] = "agent_auto_corrected"
  1097. if not corrected_answer:
  1098. plan_validation = first_plan_validation + ["自动修正服务调用失败"]
  1099. elif not looks_like_complete_training_plan(corrected_answer):
  1100. plan_validation = ["自动修正结果不是完整训练计划"]
  1101. else:
  1102. plan_validation = validate_generated_training_plan(
  1103. corrected_answer,
  1104. enforceable_memories,
  1105. expected_plan_subject,
  1106. recovery=recovery_snapshot,
  1107. safety_constraints=list(resolved_plan_context.get("active_safety_constraints") or []),
  1108. explicitly_requested=set((resolved_plan_context.get("muscle_recovery") or {}).get("explicitly_requested") or []),
  1109. resolver=_plan_muscle_resolver,
  1110. check_subject=False,
  1111. )
  1112. corrected_alignment = await run_in_threadpool(
  1113. deps.validate_plan_goal_alignment,
  1114. corrected_answer,
  1115. user_request=message,
  1116. requested_subjects=(getattr(chat_intent, "requested_subjects", []) if chat_intent is not None else []),
  1117. fallback_subject=expected_plan_subject,
  1118. weekly_subject=str(resolved_plan_context.get("scheduled_subject") or ""),
  1119. schedule_decision=str(resolved_plan_context.get("decision") or "follow_schedule"),
  1120. allow_external_models=external_models_enabled,
  1121. )
  1122. if not corrected_alignment.get("passed"):
  1123. missing = "、".join(corrected_alignment.get("missing_subjects") or [expected_plan_subject])
  1124. plan_validation.append(f"计划未覆盖用户要求的训练目标:{missing}")
  1125. plan_auto_correction["final_violations"] = list(plan_validation)
  1126. plan_auto_correction["passed"] = not plan_validation
  1127. if plan_validation:
  1128. artifact = None
  1129. answer = (corrected_answer or answer) + "\n\n## 自动修正后仍未通过计划校验\n" + "\n".join(
  1130. f"- {item}" for item in plan_validation
  1131. ) + "\n本次不提供可保存的训练计划,请调整限制或训练目标后重试。"
  1132. else:
  1133. artifact = corrected_artifact
  1134. answer = corrected_answer
  1135. if pending_reply_prefix:
  1136. answer = pending_reply_prefix + "\n\n" + answer
  1137. if artifact is not None and not plan_validation:
  1138. # BUG-05:校验通过后立刻在服务端留一份完整正文;自动修正通过
  1139. # 的计划也必须走同一条服务端草稿链。
  1140. draft = deps.plan_draft_cache.remember(
  1141. content=str(artifact.get("content") or ""),
  1142. subject=str(artifact.get("subject") or ""),
  1143. title=str(artifact.get("title") or ""),
  1144. suggested_date=str(artifact.get("suggested_date") or ""),
  1145. )
  1146. artifact["draft_id"] = draft.id
  1147. if artifact is not None or first_plan_validation:
  1148. try:
  1149. usage_violations = first_plan_validation or plan_validation
  1150. for fact_id, detail in plan_validation_fact_usage(
  1151. enforceable_memories, usage_violations
  1152. ):
  1153. deps.info_store.log_fact_usage(
  1154. [fact_id],
  1155. action="plan_auto_correction" if first_plan_validation else "plan_validation",
  1156. detail=(detail + (";自动修正通过" if first_plan_validation and not plan_validation else ""))[:500],
  1157. )
  1158. except (MemoryStoreDegradedError, OSError):
  1159. logger.exception("记忆使用日志保存失败")
  1160. response_artifact = artifact or profile_update_artifact or pending_view_artifact
  1161. if response_artifact is None and source == "chat" and any(
  1162. word in message for word in ("饮食", "营养", "摄入", "碳水", "蛋白质", "脂肪", "热量")
  1163. ):
  1164. response_artifact = {
  1165. "type": "nutrition_records",
  1166. "default_date": datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat(),
  1167. }
  1168. response_extra: dict[str, object] = {
  1169. "plan_context": resolved_plan_context,
  1170. "workflow_state": str(
  1171. state_after_generation(artifact=artifact, validation_failed=bool(plan_validation))
  1172. ),
  1173. }
  1174. if profile_update_artifact is not None:
  1175. response_extra["profile_update"] = profile_update_artifact
  1176. if health_risk is not None:
  1177. response_extra["health_risk"] = {
  1178. "level": health_risk.level,
  1179. "signals": list(health_risk.labels),
  1180. }
  1181. if immediate_memory_candidate is not None:
  1182. response_extra["memory_candidate"] = immediate_memory_candidate
  1183. if memory_candidates:
  1184. response_extra["memory_candidates"] = memory_candidates
  1185. if plan_validation:
  1186. response_extra["plan_validation"] = {"passed": False, "violations": plan_validation}
  1187. elif artifact and artifact.get("type") == "training_plan":
  1188. response_extra["plan_validation"] = {"passed": True, "violations": []}
  1189. if plan_auto_correction["attempted"]:
  1190. response_extra["plan_auto_correction"] = plan_auto_correction
  1191. return _chat_response(
  1192. answer,
  1193. artifact=response_artifact,
  1194. source=pending_view_source or "agent",
  1195. **response_extra,
  1196. )
  1197. except HelloAgentsException:
  1198. logger.exception("Agent 模型配置或调用失败")
  1199. return _chat_response(
  1200. "模型服务当前不可用;健康数据查询仍可通过“查看本周数据”使用本地汇总。",
  1201. status_code=503,
  1202. )
  1203. except Exception: # noqa: BLE001
  1204. logger.exception("Agent 对话处理失败")
  1205. return _chat_response("服务暂时不可用,请稍后重试。", status_code=500)