Song commited on
Commit ·
b55a0b9
1
Parent(s): 54072de
readme_rag
Browse files
README.md
CHANGED
|
@@ -7,395 +7,414 @@ sdk: docker
|
|
| 7 |
app_port: 7860
|
| 8 |
---
|
| 9 |
|
| 10 |
-
# 銀髮餐桌助手
|
| 11 |
-
|
| 12 |
-
專為台灣銀髮族設計的AI營養飲食顧問服務後端,提供REST API接口和Gradio聊天界面。
|
| 13 |
-
|
| 14 |
-
## 項目概述
|
| 15 |
-
|
| 16 |
-
銀髮餐桌助手是一個結合AI技術的智能營養顧問系統,專為台灣銀髮族(65歲以上)提供個性化飲食建議和營養諮詢。系統採用FastAPI框架構建,提供完整的API接口和用戶友好的Gradio聊天界面。
|
| 17 |
-
|
| 18 |
-
## 核心功能
|
| 19 |
-
|
| 20 |
-
### 🔐 身份驗證與授權
|
| 21 |
-
- 基於Supabase Auth的JWT身份驗證
|
| 22 |
-
- 支持多種用戶角色(user、family、admin)
|
| 23 |
-
- 角色基礎的訪問控制(RBAC)
|
| 24 |
-
|
| 25 |
-
### 👤 用戶資料管理
|
| 26 |
-
- 用戶檔案創建與更新
|
| 27 |
-
- 健康狀況和飲食偏好管理
|
| 28 |
-
- 個人化營養建議基礎
|
| 29 |
-
|
| 30 |
-
### 💬 AI聊天諮詢
|
| 31 |
-
- 智能營養飲食對話
|
| 32 |
-
- 基於RAG的知識檢索增強生成
|
| 33 |
-
- 支持個人化回應(基於用戶檔案)
|
| 34 |
-
- Gradio無登入聊天界面
|
| 35 |
-
|
| 36 |
-
### 🍽️ 菜單管理
|
| 37 |
-
- 台灣在地銀髮友善餐點
|
| 38 |
-
- 營養成分分析
|
| 39 |
-
- 飲食標籤分類
|
| 40 |
-
- 季節性和健康條件適配
|
| 41 |
-
|
| 42 |
-
### 🛒 訂單管理
|
| 43 |
-
- 餐點訂購功能
|
| 44 |
-
- Stripe支付集成
|
| 45 |
-
- 訂單狀態追蹤
|
| 46 |
-
- 營養統計分析
|
| 47 |
-
|
| 48 |
-
### 💰 捐款系統
|
| 49 |
-
- 匿名和實名捐款支持
|
| 50 |
-
- Stripe支付處理
|
| 51 |
-
- 捐款記錄管理
|
| 52 |
-
|
| 53 |
-
### 📊 營養儀表板
|
| 54 |
-
- 個人營養攝取統計
|
| 55 |
-
- 飲食習慣分析
|
| 56 |
-
- 家庭成員健康監控
|
| 57 |
-
|
| 58 |
-
## 技術架構
|
| 59 |
-
|
| 60 |
-
### 核心技術棧
|
| 61 |
-
- **FastAPI** - 高性能異步API框架
|
| 62 |
-
- **SQLModel** - Python ORM與數據建模
|
| 63 |
-
- **PostgreSQL** - 主數據庫(通過Supabase)
|
| 64 |
-
- **pgvector** - 向量搜索支持
|
| 65 |
-
- **Supabase** - 認證、數據庫和向量存儲
|
| 66 |
-
- **OpenAI** - AI模型和向量嵌入
|
| 67 |
-
- **LangChain** - RAG實現框架
|
| 68 |
-
- **Stripe** - 支付處理
|
| 69 |
-
- **Gradio** - 聊天界面
|
| 70 |
-
|
| 71 |
-
### 系統架構
|
| 72 |
-
```
|
| 73 |
-
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
| 74 |
-
│ Frontend │ │ Backend API │ │ External │
|
| 75 |
-
│ (React/Vue) │◄──►│ (FastAPI) │◄──►│ Services │
|
| 76 |
-
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
| 77 |
-
│
|
| 78 |
-
▼
|
| 79 |
-
┌─────────────────┐
|
| 80 |
-
│ Database │
|
| 81 |
-
│ (Supabase │
|
| 82 |
-
│ PostgreSQL) │
|
| 83 |
-
└─────────────────┘
|
| 84 |
-
```
|
| 85 |
|
| 86 |
-
|
| 87 |
|
| 88 |
-
##
|
| 89 |
|
| 90 |
-
|
| 91 |
-
- PostgreSQL 13+ (通過Supabase)
|
| 92 |
-
- Supabase項目
|
| 93 |
-
- OpenAI API Key
|
| 94 |
-
- Stripe賬戶
|
| 95 |
|
| 96 |
-
###
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
|
| 101 |
-
# Supabase Configuration
|
| 102 |
-
SUPABASE_URL=your_supabase_project_url
|
| 103 |
-
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key
|
| 104 |
-
SUPABASE_ANON_KEY=your_supabase_anon_key
|
| 105 |
|
| 106 |
-
|
| 107 |
-
DATABASE_URL=postgresql+asyncpg://postgres:[YOUR_PASSWORD]@db.[YOUR_PROJECT_ID].supabase.co:5432/postgres
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
OPENAI_API_KEY=your_openai_api_key
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
STRIPE_WEBHOOK_SECRET=whsec_your_stripe_webhook_secret
|
| 116 |
|
| 117 |
-
#
|
| 118 |
-
JWT_SECRET=your_jwt_secret_key
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
FRONTEND_URL=http://localhost:5173
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
```
|
| 133 |
|
| 134 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
``
|
| 137 |
-
# 克隆項目
|
| 138 |
-
git clone <repository-url>
|
| 139 |
-
cd silver-table-assistant/backend
|
| 140 |
|
| 141 |
-
|
| 142 |
-
python -m venv venv
|
| 143 |
-
source venv/bin/activate # Linux/Mac
|
| 144 |
-
# 或 venv\Scripts\activate # Windows
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
```
|
| 149 |
|
| 150 |
-
###
|
| 151 |
|
| 152 |
-
|
| 153 |
-
```bash
|
| 154 |
-
# 啟動FastAPI服務(自動重載)
|
| 155 |
-
python app.py
|
| 156 |
|
| 157 |
-
#
|
| 158 |
-
uvicorn app:app --reload --host 0.0.0.0 --port 8000
|
| 159 |
-
```
|
| 160 |
|
| 161 |
-
###
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
| 165 |
```
|
| 166 |
|
| 167 |
-
###
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
|
| 176 |
-
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
|
| 179 |
|
| 180 |
-
```
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
```
|
| 183 |
|
| 184 |
-
###
|
| 185 |
|
| 186 |
-
|
| 187 |
-
- `GET /api/profiles` - 獲取用戶資料列表
|
| 188 |
-
- `POST /api/profiles` - 創建或更新用戶資料
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
-
|
| 195 |
-
- `GET /api/menu` - 獲取完整菜單
|
| 196 |
|
| 197 |
-
###
|
| 198 |
-
- `POST /api/orders` - 創建新訂單(需要認證)
|
| 199 |
|
| 200 |
-
|
| 201 |
-
- `POST /api/donations` - 創建捐款(支持匿名)
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
##
|
| 207 |
-
- `GET /api/dashboard/{profile_id}` - 獲取營養統計(需要family角色)
|
| 208 |
|
| 209 |
-
###
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
-d '{
|
| 217 |
-
"display_name": "張爺爺",
|
| 218 |
-
"age": 75,
|
| 219 |
-
"health_condition": "高血壓",
|
| 220 |
-
"dietary_restrictions": "低鈉飲食"
|
| 221 |
-
}'
|
| 222 |
```
|
| 223 |
|
| 224 |
-
###
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
| 233 |
```
|
| 234 |
|
| 235 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
-
|
| 238 |
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
##
|
| 243 |
-
訂單表,記錄食物訂購和支付信息。
|
| 244 |
|
| 245 |
-
###
|
| 246 |
-
捐款表,管理捐款信息和狀態。
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
-
###
|
| 252 |
-
聊天記錄表,存儲用戶與AI的對話歷史。
|
| 253 |
|
| 254 |
-
|
|
|
|
| 255 |
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
| 261 |
```
|
| 262 |
|
| 263 |
-
##
|
| 264 |
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
-
|
| 268 |
-
```bash
|
| 269 |
-
# 創建部署所需文件
|
| 270 |
-
touch README.md
|
| 271 |
-
echo "fastapi>=0.104.0" > requirements.txt
|
| 272 |
-
echo "uvicorn[standard]>=0.24.0" >> requirements.txt
|
| 273 |
-
# 添加其他必要依賴
|
| 274 |
-
```
|
| 275 |
|
| 276 |
-
|
| 277 |
-
在Hugging Face Spaces設置中添加所有必要的環境變量。
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
###
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
|
| 291 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 292 |
|
| 293 |
-
|
| 294 |
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
-
|
| 298 |
-
```
|
| 299 |
|
| 300 |
-
|
| 301 |
-
```yaml
|
| 302 |
-
version: '3.8'
|
| 303 |
-
services:
|
| 304 |
-
backend:
|
| 305 |
-
build: .
|
| 306 |
-
ports:
|
| 307 |
-
- "8000:8000"
|
| 308 |
-
environment:
|
| 309 |
-
- ENVIRONMENT=production
|
| 310 |
-
env_file:
|
| 311 |
-
- .env
|
| 312 |
-
```
|
| 313 |
|
| 314 |
-
#### 構建和運行
|
| 315 |
```bash
|
| 316 |
-
|
| 317 |
-
|
|
|
|
| 318 |
|
| 319 |
-
#
|
|
|
|
| 320 |
|
| 321 |
-
#
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
3. 設置啟動命令:`uvicorn app:app --host 0.0.0.0 --port $PORT`
|
| 325 |
|
| 326 |
-
#
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
-
#### Heroku
|
| 332 |
```bash
|
| 333 |
-
# 創建
|
| 334 |
-
|
|
|
|
|
|
|
| 335 |
|
| 336 |
-
#
|
| 337 |
-
|
| 338 |
-
git commit -m "Deploy to Heroku"
|
| 339 |
-
git push heroku main
|
| 340 |
```
|
| 341 |
|
| 342 |
-
##
|
| 343 |
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
-
|
| 347 |
|
| 348 |
```bash
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
```
|
| 351 |
|
| 352 |
-
###
|
| 353 |
|
| 354 |
-
|
| 355 |
-
- 返回服務狀態、版本信息和數據庫連接狀態
|
| 356 |
|
| 357 |
-
|
|
|
|
|
|
|
| 358 |
|
| 359 |
-
|
| 360 |
-
-
|
| 361 |
-
|
| 362 |
|
| 363 |
-
##
|
| 364 |
|
| 365 |
-
|
| 366 |
-
-
|
| 367 |
-
-
|
| 368 |
-
|
| 369 |
|
| 370 |
-
###
|
| 371 |
-
- 敏感數據加密存儲
|
| 372 |
-
- HTTPS強制使用
|
| 373 |
-
- CORS配置優化
|
| 374 |
|
| 375 |
-
|
| 376 |
-
-
|
| 377 |
-
-
|
| 378 |
-
- SQL注入防護
|
| 379 |
|
| 380 |
## 故障排除
|
| 381 |
|
| 382 |
### 常見問題
|
| 383 |
|
| 384 |
-
1. **
|
| 385 |
-
|
| 386 |
-
|
|
|
|
| 387 |
|
| 388 |
-
2. **
|
| 389 |
-
-
|
| 390 |
-
- 檢查
|
| 391 |
|
| 392 |
-
3. **
|
| 393 |
-
-
|
| 394 |
-
-
|
| 395 |
|
| 396 |
-
4. **
|
| 397 |
-
- 檢查
|
| 398 |
-
- 確認
|
| 399 |
|
| 400 |
### 調試模式
|
| 401 |
|
|
@@ -404,42 +423,31 @@ LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR
|
|
| 404 |
export LOG_LEVEL=DEBUG
|
| 405 |
python app.py
|
| 406 |
|
| 407 |
-
# 或使用uvicorn
|
| 408 |
uvicorn app:app --reload --log-level debug
|
| 409 |
```
|
| 410 |
|
| 411 |
-
##
|
| 412 |
|
| 413 |
-
###
|
| 414 |
-
1. Fork項目
|
| 415 |
-
2. 創建功能分支
|
| 416 |
-
3. 提交變更
|
| 417 |
-
4. 創建Pull Request
|
| 418 |
|
| 419 |
-
|
| 420 |
-
- 遵循PEP 8 Python代碼風格
|
| 421 |
-
- 添加適當的文檔字符串
|
| 422 |
-
- 編寫單元測試
|
| 423 |
|
| 424 |
-
### 測試
|
| 425 |
```bash
|
| 426 |
-
#
|
| 427 |
-
pytest tests/
|
| 428 |
-
|
| 429 |
-
# 測試覆蓋率
|
| 430 |
-
pytest --cov=app tests/
|
| 431 |
```
|
| 432 |
|
| 433 |
-
##
|
| 434 |
|
| 435 |
-
|
|
|
|
| 436 |
|
| 437 |
-
##
|
| 438 |
|
| 439 |
-
-
|
| 440 |
-
-
|
| 441 |
-
-
|
| 442 |
|
| 443 |
---
|
| 444 |
|
| 445 |
-
**重要提醒**:本系統僅提供營養建議,無法替代專業醫療諮詢。如有健康問題,請諮詢專業醫師。
|
|
|
|
| 7 |
app_port: 7860
|
| 8 |
---
|
| 9 |
|
| 10 |
+
# 銀髮餐桌助手 - RAG 系統
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
本文件描述銀髮餐桌助手的 RAG(Retrieval-Augmented Generation)系統架構與實作細節。
|
| 13 |
|
| 14 |
+
## RAG 系統概述
|
| 15 |
|
| 16 |
+
銀髮餐桌助手採用 RAG 技術為台灣銀髮族(65歲以上)提供智能營養飲食諮詢服務。RAG 系統透過檢索相關知識庫文檔,增強 AI 回應的準確性和可靠性,確保所有營養建議基於權威來源。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
### 核心功能
|
| 19 |
|
| 20 |
+
- **知識檢索**:基於用戶問題從知識庫中檢索相關文檔
|
| 21 |
+
- **相似性搜索**:使用向量嵌入實現語義級相似性匹配
|
| 22 |
+
- **文檔增強生成**:將檢索到的文檔作為上下文,提升 AI 回應品質
|
| 23 |
+
- **個人化回應**:結合用戶健康檔案提供客製化建議
|
| 24 |
|
| 25 |
+
## 知識庫來源
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
知識庫位於 [`backend/data/`](backend/data/) 目錄,包含以下類型的文檔:
|
|
|
|
| 28 |
|
| 29 |
+
### 主要文檔
|
|
|
|
| 30 |
|
| 31 |
+
| 文件 | 內容 |
|
| 32 |
+
|------|------|
|
| 33 |
+
| `慢性病飲食原則.md` | 糖尿病、高血壓、高脂血症等慢性病飲食指南 |
|
|
|
|
| 34 |
|
| 35 |
+
### 文檔格式支援
|
|
|
|
| 36 |
|
| 37 |
+
- **Markdown (.md)**:主要知識庫格式
|
| 38 |
+
- **PDF (.pdf)**:支援 PDF 文件載入
|
| 39 |
|
| 40 |
+
所有文檔經過處理後存入向量資料庫,供相似性搜索使用。
|
|
|
|
| 41 |
|
| 42 |
+
## 系統架構流程圖
|
|
|
|
| 43 |
|
| 44 |
+
```
|
| 45 |
+
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
| 46 |
+
│ User Query │────►│ Chat Service │────►│ RAG Service │
|
| 47 |
+
│ (問題輸入) │ │ (聊天服務) │ │ (RAG服務) │
|
| 48 |
+
└─────────────────┘ └────────┬────────┘ └────────┬────────┘
|
| 49 |
+
│ │
|
| 50 |
+
│ ▼
|
| 51 |
+
│ ┌─────────────────┐
|
| 52 |
+
│ │ Embeddings │
|
| 53 |
+
│ │ (向量化) │
|
| 54 |
+
│ └────────┬────────┘
|
| 55 |
+
│ │
|
| 56 |
+
│ ▼
|
| 57 |
+
│ ┌─────────────────┐
|
| 58 |
+
│ │ Supabase │
|
| 59 |
+
│ │ pgvector │
|
| 60 |
+
│ │ (向量資料庫) │
|
| 61 |
+
│ └────────┬────────┘
|
| 62 |
+
│ │
|
| 63 |
+
│ ▼
|
| 64 |
+
│ ┌─────────────────┐
|
| 65 |
+
│ │ Similarity │
|
| 66 |
+
│ │ Search │
|
| 67 |
+
│ │ (相似性搜索) │
|
| 68 |
+
│ └────────┬────────┘
|
| 69 |
+
│ │
|
| 70 |
+
│ ▼
|
| 71 |
+
│ ┌─────────────────┐
|
| 72 |
+
│ │ Relevant Docs │
|
| 73 |
+
│ │ (相關文檔) │
|
| 74 |
+
│ └────────┬────────┘
|
| 75 |
+
│ │
|
| 76 |
+
▼ ▼
|
| 77 |
+
┌─────────────────┐ ┌─────────────────┐
|
| 78 |
+
│ LLM Response │◄────│ Context │
|
| 79 |
+
│ (AI回應) │ │ Integration │
|
| 80 |
+
└─────────────────┘ └─────────────────┘
|
| 81 |
```
|
| 82 |
|
| 83 |
+
## 核心組件說明
|
| 84 |
+
|
| 85 |
+
### RAG 服務 ([`rag.py`](backend/rag.py))
|
| 86 |
+
|
| 87 |
+
RAG 服務是系統的核心模組,負責文檔處理和向量搜索。
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
class RAGService:
|
| 91 |
+
"""RAG service for document management and similarity search."""
|
| 92 |
+
|
| 93 |
+
def __init__(self):
|
| 94 |
+
# 初始化 OpenAI 向量化模型
|
| 95 |
+
self.embeddings = OpenAIEmbeddings(...)
|
| 96 |
+
# 初始化 Supabase 向量存儲
|
| 97 |
+
self.vector_store = SupabaseVectorStore(...)
|
| 98 |
+
# 初始化文檔分塊器
|
| 99 |
+
self.text_splitter = RecursiveCharacterTextSplitter(
|
| 100 |
+
chunk_size=1000,
|
| 101 |
+
chunk_overlap=200
|
| 102 |
+
)
|
| 103 |
+
```
|
| 104 |
|
| 105 |
+
### 聊天服務 ([`chat_service.py`](backend/chat_service.py))
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
聊天服務整合 RAG 能力,提供 AI 對話功能。
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
```python
|
| 110 |
+
class ChatService:
|
| 111 |
+
"""Chat service for AI-powered conversations with RAG integration."""
|
| 112 |
+
|
| 113 |
+
def __init__(self):
|
| 114 |
+
# 初始化 LLM 模型
|
| 115 |
+
self.llm = ChatOpenAI(...)
|
| 116 |
+
# 整合 RAG 服務
|
| 117 |
+
self.rag_service = get_rag_service()
|
| 118 |
```
|
| 119 |
|
| 120 |
+
### 資料庫設置 ([`setup_rag_db.py`](backend/setup_rag_db.py))
|
| 121 |
|
| 122 |
+
設置 pgvector 擴展和文檔表結構。
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
## 文檔處理流程
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
### 流程步驟
|
| 127 |
+
|
| 128 |
+
```
|
| 129 |
+
┌─────────��───┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
| 130 |
+
│ 載入文檔 │───►│ 文檔分塊 │───►│ 向量化 │───►│ 存入資料庫 │
|
| 131 |
+
│ Loader │ │ Chunker │ │ Embedding │ │ Storage │
|
| 132 |
+
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
|
| 133 |
```
|
| 134 |
|
| 135 |
+
### 1. 文檔載入
|
| 136 |
|
| 137 |
+
支援多種文檔載入器:
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
# PDF 載入
|
| 141 |
+
loader = PyPDFLoader(str(file_path))
|
| 142 |
+
documents = loader.load()
|
| 143 |
+
|
| 144 |
+
# Markdown 載入
|
| 145 |
+
loader = UnstructuredMarkdownLoader(str(file_path))
|
| 146 |
+
documents = loader.load()
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
### 2. 文檔分塊
|
| 150 |
|
| 151 |
+
使用 [`RecursiveCharacterTextSplitter`](backend/rag.py:66) 進行智慧分塊:
|
| 152 |
|
| 153 |
+
- **chunk_size**:1000 字元
|
| 154 |
+
- **chunk_overlap**:200 字元重疊
|
| 155 |
+
- **is_separator_regex**:false(使用純文字分隔)
|
| 156 |
|
| 157 |
+
每個區塊包含以下元數據:
|
| 158 |
|
| 159 |
+
```python
|
| 160 |
+
chunk.metadata = {
|
| 161 |
+
"source": "文件路徑",
|
| 162 |
+
"file_name": "檔案名稱",
|
| 163 |
+
"chunk_id": "唯一識別碼"
|
| 164 |
+
}
|
| 165 |
```
|
| 166 |
|
| 167 |
+
### 3. 向量化
|
| 168 |
|
| 169 |
+
使用 OpenAI Embeddings 模型將文本轉換為向量:
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
```python
|
| 172 |
+
embeddings = OpenAIEmbeddings(
|
| 173 |
+
model="azure-text-embedding-3-large",
|
| 174 |
+
openai_api_key=api_key
|
| 175 |
+
)
|
| 176 |
+
# 支援 LiteLLM 相容端點
|
| 177 |
+
```
|
| 178 |
|
| 179 |
+
向量維度:**3072**
|
|
|
|
| 180 |
|
| 181 |
+
### 4. 向量存儲
|
|
|
|
| 182 |
|
| 183 |
+
存入 Supabase pgvector 向量資料庫:
|
|
|
|
| 184 |
|
| 185 |
+
```python
|
| 186 |
+
vector_store = SupabaseVectorStore(
|
| 187 |
+
client=supabase_client,
|
| 188 |
+
embedding=embeddings,
|
| 189 |
+
table_name="documents",
|
| 190 |
+
query_name="match_documents"
|
| 191 |
+
)
|
| 192 |
+
```
|
| 193 |
|
| 194 |
+
## 相似性搜索
|
|
|
|
| 195 |
|
| 196 |
+
### 基本搜索
|
| 197 |
|
| 198 |
+
```python
|
| 199 |
+
async def get_relevant_documents(self, query: str, k: int = 8) -> List[Document]:
|
| 200 |
+
"""執行相似性搜索檢索相關文檔"""
|
| 201 |
+
results = await self.vector_store.asimilarity_search(query, k=k)
|
| 202 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
```
|
| 204 |
|
| 205 |
+
### 帶分數的搜索
|
| 206 |
+
|
| 207 |
+
```python
|
| 208 |
+
async def get_relevant_documents_with_scores(
|
| 209 |
+
self,
|
| 210 |
+
query: str,
|
| 211 |
+
k: int = 8,
|
| 212 |
+
score_threshold: float = 0.7
|
| 213 |
+
) -> List[Document]:
|
| 214 |
+
"""執行帶分數閾值的相似性搜索"""
|
| 215 |
```
|
| 216 |
|
| 217 |
+
### 分頁搜索
|
| 218 |
+
|
| 219 |
+
```python
|
| 220 |
+
async def get_relevant_documents_paginated(
|
| 221 |
+
self,
|
| 222 |
+
query: str,
|
| 223 |
+
page: int = 1,
|
| 224 |
+
page_size: int = 10,
|
| 225 |
+
score_threshold: Optional[float] = None
|
| 226 |
+
) -> Dict[str, Any]:
|
| 227 |
+
"""執行分頁相似性搜索"""
|
| 228 |
+
```
|
| 229 |
+
|
| 230 |
+
### 搜索結果快取
|
| 231 |
|
| 232 |
+
系統使用文檔快取機制(TTL: 30 分鐘)優化效能:
|
| 233 |
|
| 234 |
+
```python
|
| 235 |
+
@cache_result(document_cache, "rag_documents", ttl=1800)
|
| 236 |
+
async def get_relevant_documents(self, query: str, k: int = 8):
|
| 237 |
+
...
|
| 238 |
+
```
|
| 239 |
|
| 240 |
+
## AI 對話整合
|
|
|
|
| 241 |
|
| 242 |
+
### 對話流程
|
|
|
|
| 243 |
|
| 244 |
+
1. 接收用戶問題
|
| 245 |
+
2. 檢索相關文檔(k=6)
|
| 246 |
+
3. 獲取用戶健康檔案
|
| 247 |
+
4. 格式化上下文資訊
|
| 248 |
+
5. 組合系統提示詞
|
| 249 |
+
6. 串流回應生成
|
| 250 |
|
| 251 |
+
### 系統提示詞
|
|
|
|
| 252 |
|
| 253 |
+
```python
|
| 254 |
+
system_prompt = """你是「銀髮餐桌助手」,專為台灣銀髮族設計的AI營養飲食顧問助手。
|
| 255 |
|
| 256 |
+
角色定位:
|
| 257 |
+
- 溫暖、耐心、專業的營養飲食顧問
|
| 258 |
+
- 專門為台灣銀髮族(65歲以上)提供飲食建議
|
| 259 |
+
- 熟悉台灣在地食材、飲食文化和生活習慣
|
| 260 |
|
| 261 |
+
核心原則:
|
| 262 |
+
1. 嚴格遵循台灣衛福部(MOHW)的營養指導原則
|
| 263 |
+
2. 僅提供營養建議,絕不進行醫療診斷
|
| 264 |
+
3. 針對銀髮族的特殊營養需求
|
| 265 |
+
4. 考慮台灣在地飲食文化"""
|
| 266 |
```
|
| 267 |
|
| 268 |
+
### 上下文整合
|
| 269 |
|
| 270 |
+
```python
|
| 271 |
+
def format_context_information(self, user_context, relevant_docs) -> str:
|
| 272 |
+
"""格式化用戶上下文和相關文檔"""
|
| 273 |
+
# 組合用戶背景資訊
|
| 274 |
+
# 組合相關營養指南文檔
|
| 275 |
+
return formatted_context
|
| 276 |
+
```
|
| 277 |
|
| 278 |
+
## API 端點
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
### RAG 相關端點
|
|
|
|
| 281 |
|
| 282 |
+
| 端點 | 方法 | 說明 |
|
| 283 |
+
|------|------|------|
|
| 284 |
+
| `/api/chat` | POST | AI 聊天諮詢(含 RAG) |
|
| 285 |
+
| `/rag/load` | POST | 載入知識庫 |
|
| 286 |
+
| `/rag/search` | GET | 相似性搜索 |
|
| 287 |
+
| `/rag/count` | GET | 獲取文檔數量 |
|
| 288 |
+
| `/rag/clear` | DELETE | 清除知識庫 |
|
| 289 |
+
| `/` | GET | Gradio 聊天界面 |
|
| 290 |
|
| 291 |
+
### 聊天請求範例
|
| 292 |
|
| 293 |
+
```bash
|
| 294 |
+
curl -X POST "http://localhost:8000/api/chat" \
|
| 295 |
+
-H "Authorization: Bearer <token>" \
|
| 296 |
+
-H "Content-Type: application/json" \
|
| 297 |
+
-d '{
|
| 298 |
+
"message": "請問銀髮族應該如何補充蛋白質?",
|
| 299 |
+
"profile_id": "uuid-string"
|
| 300 |
+
}'
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
### 知識庫載入請求
|
| 304 |
|
| 305 |
+
```bash
|
| 306 |
+
curl -X POST "http://localhost:8000/rag/load" \
|
| 307 |
+
-H "Authorization: Bearer <token>"
|
| 308 |
+
```
|
| 309 |
|
| 310 |
+
## 快速開始
|
|
|
|
| 311 |
|
| 312 |
+
### 前置要求
|
| 313 |
|
| 314 |
+
- Python 3.8+
|
| 315 |
+
- PostgreSQL 13+(通過 Supabase,啟用 pgvector)
|
| 316 |
+
- Supabase 專案
|
| 317 |
+
- OpenAI API Key 或 LiteLLM API Key
|
| 318 |
|
| 319 |
+
### 環境變數配置
|
|
|
|
| 320 |
|
| 321 |
+
複製 `.env.example` 到 `.env` 並填入以下配置:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
|
|
|
| 323 |
```bash
|
| 324 |
+
# Supabase Configuration
|
| 325 |
+
SUPABASE_URL=your_supabase_project_url
|
| 326 |
+
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key
|
| 327 |
|
| 328 |
+
# Database URL for pgvector (Supabase PostgreSQL)
|
| 329 |
+
DATABASE_URL=postgresql+asyncpg://postgres:[YOUR_PASSWORD]@db.[YOUR_PROJECT_ID].supabase.co:5432/postgres
|
| 330 |
|
| 331 |
+
# OpenAI Configuration (or LiteLLM)
|
| 332 |
+
OPENAI_API_KEY=your_openai_api_key
|
| 333 |
+
OPENAI_BASE_URL=your_openai_base_url # Optional, for LiteLLM/Azure
|
|
|
|
| 334 |
|
| 335 |
+
# Or use LiteLLM directly
|
| 336 |
+
LITELLM_API_KEY=your_litellm_api_key
|
| 337 |
+
LITELLM_BASE_URL=https://your-litellm-endpoint/
|
| 338 |
+
|
| 339 |
+
# Server Configuration
|
| 340 |
+
HOST=0.0.0.0
|
| 341 |
+
PORT=8000
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
### 安裝依賴
|
| 345 |
|
|
|
|
| 346 |
```bash
|
| 347 |
+
# 創建虛擬環境
|
| 348 |
+
python -m venv venv
|
| 349 |
+
source venv/bin/activate # Linux/Mac
|
| 350 |
+
# 或 venv\Scripts\activate # Windows
|
| 351 |
|
| 352 |
+
# 安裝依賴
|
| 353 |
+
pip install -r requirements.txt
|
|
|
|
|
|
|
| 354 |
```
|
| 355 |
|
| 356 |
+
### 資料庫設置
|
| 357 |
|
| 358 |
+
```bash
|
| 359 |
+
# 設置 pgvector 和文檔表
|
| 360 |
+
python setup_rag_db.py
|
| 361 |
+
```
|
| 362 |
|
| 363 |
+
### 啟動服務
|
| 364 |
|
| 365 |
```bash
|
| 366 |
+
# 啟動 FastAPI 服務
|
| 367 |
+
python app.py
|
| 368 |
+
|
| 369 |
+
# 或使用 uvicorn
|
| 370 |
+
uvicorn app:app --reload --host 0.0.0.0 --port 8000
|
| 371 |
```
|
| 372 |
|
| 373 |
+
### 載入知識庫
|
| 374 |
|
| 375 |
+
知識庫會在服務啟動時自動載入,或可手動觸發:
|
|
|
|
| 376 |
|
| 377 |
+
```bash
|
| 378 |
+
# 通過 API
|
| 379 |
+
curl -X POST "http://localhost:8000/rag/load"
|
| 380 |
|
| 381 |
+
# 或直接運行
|
| 382 |
+
python -m rag
|
| 383 |
+
```
|
| 384 |
|
| 385 |
+
### 測試 RAG 系統
|
| 386 |
|
| 387 |
+
```bash
|
| 388 |
+
python -m rag
|
| 389 |
+
python -m chat_service
|
| 390 |
+
```
|
| 391 |
|
| 392 |
+
### 訪問應用
|
|
|
|
|
|
|
|
|
|
| 393 |
|
| 394 |
+
- **API 文檔**: http://localhost:8000/api/docs
|
| 395 |
+
- **Gradio 聊天界面**: http://localhost:8000/
|
| 396 |
+
- **健康檢查**: http://localhost:8000/health
|
|
|
|
| 397 |
|
| 398 |
## 故障排除
|
| 399 |
|
| 400 |
### 常見問題
|
| 401 |
|
| 402 |
+
1. **pgvector 擴展未啟用**
|
| 403 |
+
```sql
|
| 404 |
+
CREATE EXTENSION IF NOT EXISTS vector;
|
| 405 |
+
```
|
| 406 |
|
| 407 |
+
2. **向量維度不匹配**
|
| 408 |
+
- 確保 embedding 向量維度為 3072
|
| 409 |
+
- 檢查資料庫表結構:`embedding vector(3072)`
|
| 410 |
|
| 411 |
+
3. **SupabaseVectorStore 兼容性問題**
|
| 412 |
+
- 系統已內建手動 RPC 回退機制
|
| 413 |
+
- 使用 `match_documents` 函數直接執行相似性搜索
|
| 414 |
|
| 415 |
+
4. **知識庫載入失敗**
|
| 416 |
+
- 檢查 `backend/data/` 目錄存在且包含文件
|
| 417 |
+
- 確認文件格式為支援的類型(.md, .pdf)
|
| 418 |
|
| 419 |
### 調試模式
|
| 420 |
|
|
|
|
| 423 |
export LOG_LEVEL=DEBUG
|
| 424 |
python app.py
|
| 425 |
|
| 426 |
+
# 或使用 uvicorn
|
| 427 |
uvicorn app:app --reload --log-level debug
|
| 428 |
```
|
| 429 |
|
| 430 |
+
## 監控與日誌
|
| 431 |
|
| 432 |
+
### 日誌配置
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
+
系統使用 Python 標準日誌庫:
|
|
|
|
|
|
|
|
|
|
| 435 |
|
|
|
|
| 436 |
```bash
|
| 437 |
+
LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
```
|
| 439 |
|
| 440 |
+
### 健康檢查
|
| 441 |
|
| 442 |
+
- `GET /health` - 服務健康狀態檢查
|
| 443 |
+
- 返回服務狀態、版本信息和資料庫連接狀態
|
| 444 |
|
| 445 |
+
## 安全考量
|
| 446 |
|
| 447 |
+
- 知識庫搜索無需認證(匿名用戶也可使用)
|
| 448 |
+
- 用戶健康檔案相關操作需要 JWT 認證
|
| 449 |
+
- 向量資料庫連接使用服務層級密鑰
|
| 450 |
|
| 451 |
---
|
| 452 |
|
| 453 |
+
**重要提醒**:本系統僅提供營養建議,無法替代專業醫療諮詢。如有健康問題,請諮詢專業醫師。
|