Files
fastapi/README.md
T
2026-06-03 15:51:46 +08:00

144 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 医疗问诊 Agent 后端
医疗问诊 Agent 是宿主医疗教学平台中的问诊训练子功能。后端基于 FastAPI 构建,负责病例读取、训练会话、多轮问诊、检查申请、诊断治疗提交、AI 评价、PDF 报告导出和历史记录查询。
## 技术栈
- Python 3.11
- FastAPI
- SQLAlchemy 2.x
- MySQL
- Redis
- OpenAI-compatible LLM Adapter
- ReportLab PDF
## 核心功能
- Django 用户中心 token 校验
- 病例列表与病例详情
- 病例 SQL 安全导入与删除
- 训练会话创建
- 多轮问诊与 SSE 流式回复
- 练习提示
- 检查/检验申请
- 诊断与治疗提交
- AI 评价报告生成
- 评分明细落库
- PDF 报告导出
- 历史评价查询
- LLM Fast/Reason 测试
## 本地启动
```powershell
cd backend
python -m venv .venv
.\.venv\Scripts\activate
pip install -r requirements.txt
cd ..
copy .env.example .env
```
编辑 `.env`,填写 MySQL、Redis、Django 用户中心和 LLM 配置。
启动服务:
```powershell
cd backend
uvicorn app.main:app --host 127.0.0.1 --port 9000
```
访问:
```text
http://127.0.0.1:9000/docs
```
## Docker 启动
```powershell
copy .env.example .env
docker build -t medical-consultation-agent-backend .
docker run --env-file .env -p 9000:9000 medical-consultation-agent-backend
```
## 环境变量
关键配置见 `.env.example`
```env
DATABASE_URL=mysql+pymysql://root:<password>@mysql:3306/medical_platform?charset=utf8mb4
MYSQL_URL=mysql+aiomysql://root:<password>@mysql:3306/medical_platform?charset=utf8mb4
REDIS_URL=redis://redis:6379/0
AUTH_USER_ME_URL=http://django:8000/api/user/users/me/
LLM_BASE_URL=https://api.deepseek.com/chat/completions
LLM_API_KEY=
```
真实数据库密码、LLM Key 和 access token 只写入本地 `.env` 或部署环境变量。
## 数据库初始化与检查
数据库需先创建好,表结构由后端脚本创建和校验。
```powershell
cd backend
.\.venv\Scripts\python.exe scripts\migrate_to_new_schema.py
.\.venv\Scripts\python.exe scripts\migrate_user_department_score_detail.py
.\.venv\Scripts\python.exe scripts\check_final_schema.py
.\.venv\Scripts\python.exe scripts\check_final_demo_readiness.py
```
清空训练运行数据和本地报告文件:
```powershell
cd backend
.\.venv\Scripts\python.exe scripts\clear_training_runtime_data.py --confirm CLEAR_TRAINING_DATA --reports
```
该脚本只清理训练会话、检查申请、提交、评价记录、评分明细、审计日志和本地 PDF 报告,不删除病例、用户、科室、检查项、评分规则、提示词和知识库。
## 用户认证
前端请求医疗问诊 Agent 时携带宿主系统 access token
```http
Authorization: Bearer <access_token>
X-Entry-Scene: mac_vue_dev
```
后端会转发 token 到 Django 用户中心:
```text
GET /api/user/users/me/
```
Django 返回 200 后,后端使用返回的 `id` 作为本系统内部用户隔离 ID。前端不需要传 `X-User-Id`
验证接口:
```bash
curl -X GET "http://127.0.0.1:9000/api/v1/auth/me" \
-H "Authorization: Bearer <access_token>" \
-H "X-Entry-Scene: mac_vue_dev"
```
## 测试
```powershell
cd backend
.\.venv\Scripts\python.exe -m compileall app scripts tests
.\.venv\Scripts\python.exe tests\test_core_logic.py
.\.venv\Scripts\python.exe tests\test_api_contract.py
.\.venv\Scripts\python.exe tests\test_demo_flow.py
```
## API 文档
启动后访问:
```text
http://127.0.0.1:9000/docs
http://127.0.0.1:9000/openapi.json
```