Files
GarminHealthLab/backend/.env.example
ericwyuan c57c930949 feat(ai): AI 教练 —— 晨间简报、运动处方、趋势归因与 Copilot
数值全部在服务端算好再交给模型,模型只做解读。让模型从 CSV 里自己推
z 分数,它算错的次数足以让简报引用图表反驳它的数字。

- services/insights.py:z 分数(28 天个人基线,且**排除当天**——用一个
  值参与算出来的均值去衡量它自己,会把真实离群点摊平)、13 个月趋势斜率
  (按序数日期最小二乘,手表放充电器上一周不会压缩 x 轴)、近 7 天活动量
  对比。
- services/coach.py:三套提示词 + 回复解析,每套都配一个规则引擎版本。
  网关一次生成要几分钟,上游被限流时给一个朴素的答案,好过给一张空卡片。
- services/ai.py:多轮 chat()、SSE stream()、complete()/stream_chat(),
  以及 extract_json()——上游是推理模型,可见输出以思维链开头,所以从末尾
  倒着找最后一个配平的 JSON(字符串感知,扛得住引号里的 } 和转义引号)。
- 接口 briefing / trend-insight / copilot(SSE),缓存表 ai_insights。
- 前端:今日页晨报卡(后台生成 + 轮询升级)、全局 Copilot 浮窗、指标详情
  页归因面板。features.ai 打开。

实测(对着自建 ai-gateway):晨报一次 273 秒,缓存命中 18 毫秒——所以简报
绝不能同步阻塞首屏。网关的流式通道比阻塞通道更不可靠:同一条提示词流式
139 秒后返回「所有模型均不可用」,阻塞则成功,因此 stream_chat() 在流式零
输出时对同一模型退回非流式重试。Copilot 实测 TTFB 9ms、全程 40 秒。

顺带修两处:refresh 原来只跳过缓存读、不删行,导致「重新生成」后的轮询读
到旧行、看到 cached 就停了,用户一直盯着他刚要求替换掉的那段字;基线零方差
时原来返回 z=0.0,把「和每一条观测都不同」标成「完全正常」,改为 z=null。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 13:57:35 +08:00

92 lines
4.1 KiB
Plaintext

# --- Server ---
# BACKEND_PORT takes precedence over PORT. Prefer it: many tools inject PORT
# for the frontend, and Flask would otherwise take the React dev server's port.
BACKEND_PORT=5000
# --- Database: sqlite (default) or mariadb ---
DB_TYPE=sqlite
# SQLite file (used when DB_TYPE=sqlite)
DATABASE_PATH=./data/health.db
# MariaDB (used when DB_TYPE=mariadb) — production DB on the Oracle server
# (129.146.26.249, local MariaDB 10.3). Dedicated account over TCP 127.0.0.1;
# MARIADB_SOCKET is only needed if TCP auth is disabled for the app user.
# MARIADB_HOST=127.0.0.1
# MARIADB_PORT=3306
# MARIADB_USER=garmin
# MARIADB_PASSWORD=your_production_mariadb_password
# MARIADB_DATABASE=garmin_health_lab
# --- Auth ---
# CHANGE THIS in production! Used to sign JWTs (7-day expiry by default).
JWT_SECRET=dev_secret_change_me
JWT_EXPIRY_DAYS=7
# --- auth-hub OAuth2 provider (centralized SSO) ---
# See docs/AUTH_HUB_INTEGRATION.md for setup instructions.
#
# Base URL of the auth-hub service
AUTH_HUB_BASE_URL=http://129.146.26.249:5300
#
# OAuth2 client credentials (obtain from auth-hub.manage_clients create)
# NOTE: these must be registered against the auth-hub instance AUTH_HUB_BASE_URL
# actually points to (dev vs prod are separate databases with separate clients).
# Put the REAL values in backend/.env (gitignored) — never here.
AUTH_HUB_CLIENT_ID=your_client_id
AUTH_HUB_CLIENT_SECRET=your_client_secret
#
# Callback URL (must exactly match what's registered in auth-hub)
AUTH_HUB_REDIRECT_URI=http://129.146.26.249:8123/auth/callback
# --- CORS (comma-separated allowed front-end origins) ---
# localhost stays in the production list on purpose: CORS is not an auth
# boundary — every data route requires a valid JWT — so allowing a developer's
# dev server costs nothing and saves toggling this on every session.
CORS_ORIGIN=http://localhost:3000,http://localhost:5173
# --- AI models (text-only, large context) ---
# Put REAL keys in backend/.env — that file is gitignored. Never commit keys.
# Any model whose credentials are absent is skipped automatically.
# Self-hosted AI gateway (model id "gateway"). OpenAI-compatible; it fans out
# over nvidia/gemini/ollama itself and rotates several Gemini keys, so it
# absorbs single-vendor quota limits. Reached directly, bypassing any local
# HTTP proxy. NOTE: its NVIDIA upstream is a large reasoning model — replies
# can take 2-3 minutes, so set AI_TIMEOUT_SECONDS accordingly.
# HTTPS (Caddy, strips the /ai prefix) rather than http://…:5100 — the token
# rides in an Authorization header and should not cross the internet in clear.
AI_GATEWAY_BASE_URL=https://oracle.zichuan.xyz/ai/v1
AI_GATEWAY_TOKEN=
AI_GATEWAY_MODEL=ai-gateway-auto
# Google AI Studio -> "gemini-flash". Free-tier quota is small; 429s are common.
GEMINI_API_KEY=
# NVIDIA NIM -> "llama-70b", "nemotron-49b", "mistral-large".
# Model ids come from that account's live GET /v1/models — do not guess them.
NVIDIA_API_KEY=
# NVIDIA_BASE_URL=https://integrate.api.nvidia.com/v1
# Preference order. The first configured model answers; if it fails or times
# out, the next is tried. Read per request, so changes need no restart.
AI_MODEL_CHAIN=gateway,gemini-flash,llama-70b
# Max days of history sent (CSV-encoded). Trimmed further per model so the
# payload always fits that model's own context window.
AI_DAY_BUDGET=365
# Measured against the gateway, not guessed: a trivial prompt took 138s end to
# end, because its primary upstream emits a full chain of thought before the
# answer. Nothing user-facing blocks on this (the briefing generates in a
# background thread), but the timeout still has to clear the real latency.
AI_TIMEOUT_SECONDS=300
# Output cap. Reasoning models spend part of it thinking before they answer;
# entries that need more declare their own budget in services/ai.py.
AI_MAX_TOKENS=1024
# Output cap for the AI coach (晨报 / 趋势归因 / Copilot). Larger than
# AI_MAX_TOKENS above: the same reasoning trace is spent from this budget
# before the answer starts, and at 1024 the reply was all thinking with the
# JSON truncated away.
AI_COACH_MAX_TOKENS=4000