feat: 初始化考培练系统项目
- 从服务器拉取完整代码 - 按框架规范整理项目结构 - 配置 Drone CI 测试环境部署 - 包含后端(FastAPI)、前端(Vue3)、管理端 技术栈: Vue3 + TypeScript + FastAPI + MySQL
This commit is contained in:
166
docs/规划/后端开发拆分策略/README.md
Normal file
166
docs/规划/后端开发拆分策略/README.md
Normal file
@@ -0,0 +1,166 @@
|
||||
# 考培练系统后端开发拆分策略
|
||||
|
||||
本目录包含了考培练系统后端开发的完整拆分策略和实施指南,用于指导多个子Agent协同开发后端系统。
|
||||
|
||||
## 📁 文档结构
|
||||
|
||||
### 1. [项目脚手架结构](./项目脚手架结构.md)
|
||||
- 完整的项目目录结构
|
||||
- AI平台(Coze & Dify)集成架构
|
||||
- 配置文件示例
|
||||
- 环境变量配置
|
||||
|
||||
### 2. [开发规范文档](./开发规范文档.md)
|
||||
- Python代码规范
|
||||
- API开发规范
|
||||
- 数据库规范
|
||||
- 异常处理规范
|
||||
- 日志规范
|
||||
- 测试规范
|
||||
- Git提交规范
|
||||
- 代码审查清单
|
||||
|
||||
### 3. [模块分工指南](./模块分工指南.md)
|
||||
- 9个核心模块的详细划分
|
||||
- 每个Agent的职责范围
|
||||
- 模块间依赖关系
|
||||
- API接口定义
|
||||
- 开发时序安排
|
||||
- 模块交付标准
|
||||
|
||||
### 4. [协作机制设计](./协作机制设计.md)
|
||||
- 全局上下文共享机制
|
||||
- Agent间通信接口
|
||||
- 代码集成策略
|
||||
- 分布式事务管理
|
||||
- 错误处理与恢复
|
||||
- 监控与日志
|
||||
- 开发工具与脚本
|
||||
|
||||
### 5. [质量保证机制](./质量保证机制.md)
|
||||
- 自动化代码检查
|
||||
- 测试策略(单元/集成/性能)
|
||||
- CI/CD配置
|
||||
- 代码审查流程
|
||||
- 安全保证
|
||||
- 监控与告警
|
||||
- 发布管理
|
||||
|
||||
### 6. [统一基础代码](./统一基础代码.md)
|
||||
- 主应用入口代码
|
||||
- 系统配置管理
|
||||
- 数据库配置
|
||||
- 基础模型类
|
||||
- 认证依赖注入
|
||||
- 异常处理
|
||||
- 日志配置
|
||||
- 业务服务基类
|
||||
- 常用工具函数
|
||||
|
||||
### 7. [快速开始指南](./快速开始指南.md)
|
||||
- 环境准备
|
||||
- 项目初始化
|
||||
- 数据库初始化
|
||||
- 启动服务
|
||||
- 开发工作流
|
||||
- 模块开发指南
|
||||
- 调试技巧
|
||||
- 常见问题解决
|
||||
|
||||
## 🏗️ 系统架构概览
|
||||
|
||||
```
|
||||
考培练系统后端
|
||||
├── 认证授权模块 (Agent-Auth)
|
||||
├── 用户管理模块 (Agent-User)
|
||||
├── 课程管理模块 (Agent-Course)
|
||||
├── 考试模块 (Agent-Exam)
|
||||
├── AI陪练模块 (Agent-Training)
|
||||
├── 数据分析模块 (Agent-Analytics)
|
||||
├── 系统管理模块 (Agent-Admin)
|
||||
├── Coze集成服务 (Agent-Coze)
|
||||
└── Dify集成服务 (Agent-Dify)
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
1. **环境准备**
|
||||
```bash
|
||||
# 克隆项目
|
||||
git clone <repository-url> kaopeilian-backend
|
||||
cd kaopeilian-backend
|
||||
|
||||
# 创建虚拟环境
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
|
||||
# 安装依赖
|
||||
pip install -r requirements/dev.txt
|
||||
```
|
||||
|
||||
2. **配置环境**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 编辑.env文件配置数据库、AI平台等
|
||||
```
|
||||
|
||||
3. **初始化数据库**
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
4. **启动开发服务器**
|
||||
```bash
|
||||
make run-dev
|
||||
```
|
||||
|
||||
## 📋 开发流程
|
||||
|
||||
1. **领取任务**:根据[模块分工指南](./模块分工指南.md)领取对应模块
|
||||
2. **阅读规范**:仔细阅读[开发规范文档](./开发规范文档.md)
|
||||
3. **创建分支**:基于develop创建feature分支
|
||||
4. **编写代码**:使用[统一基础代码](./统一基础代码.md)中的基类和工具
|
||||
5. **测试验证**:按照[质量保证机制](./质量保证机制.md)进行测试
|
||||
6. **代码审查**:提交PR等待审查
|
||||
7. **合并集成**:通过审查后合并到develop分支
|
||||
|
||||
## 🤝 协作要点
|
||||
|
||||
- **统一规范**:所有Agent必须遵循相同的代码规范
|
||||
- **接口契约**:严格按照定义的接口进行开发
|
||||
- **及时沟通**:通过消息总线和日志系统保持信息同步
|
||||
- **质量第一**:确保代码质量和测试覆盖率
|
||||
- **文档完善**:及时更新API文档和设计文档
|
||||
|
||||
## 📊 项目管理
|
||||
|
||||
- **进度跟踪**:每日更新开发进度
|
||||
- **问题反馈**:使用Issue系统跟踪问题
|
||||
- **代码审查**:所有代码必须经过审查
|
||||
- **持续集成**:自动运行测试和代码检查
|
||||
|
||||
## 🛠️ 技术栈
|
||||
|
||||
- **后端框架**:Python 3.8+ + FastAPI
|
||||
- **数据库**:MySQL 8.0 + Redis
|
||||
- **ORM**:SQLAlchemy 2.0
|
||||
- **AI平台**:Coze + Dify
|
||||
- **测试框架**:pytest
|
||||
- **代码质量**:Black + isort + flake8 + mypy
|
||||
|
||||
## 📞 联系方式
|
||||
|
||||
- 技术负责人:[联系方式]
|
||||
- 项目管理:[联系方式]
|
||||
- 问题反馈:[Issue链接]
|
||||
|
||||
## 📝 更新日志
|
||||
|
||||
- 2025-01-XX:初始版本发布
|
||||
- 包含完整的项目架构设计
|
||||
- 9个核心模块的详细分工
|
||||
- 统一的开发规范和基础代码
|
||||
|
||||
---
|
||||
|
||||
**注意**:本文档会根据项目进展持续更新,请定期查看最新版本。
|
||||
1066
docs/规划/后端开发拆分策略/协作机制设计.md
Normal file
1066
docs/规划/后端开发拆分策略/协作机制设计.md
Normal file
File diff suppressed because it is too large
Load Diff
425
docs/规划/后端开发拆分策略/子agent/00-通用基础/base_prompt.md
Normal file
425
docs/规划/后端开发拆分策略/子agent/00-通用基础/base_prompt.md
Normal file
@@ -0,0 +1,425 @@
|
||||
# 通用基础提示词
|
||||
|
||||
## 🎯 核心职责定义
|
||||
|
||||
你是一个专业的全栈开发工程师,负责开发和维护考培练系统的特定模块。你的工作遵循以下原则:
|
||||
|
||||
### 基本要求
|
||||
- 使用技术栈:Python + FastAPI + MySQL + Vue3 + TypeScript
|
||||
- 遵循项目统一的代码规范和架构设计
|
||||
- 确保代码质量、安全性和可维护性
|
||||
- 与其他子agent协作,避免功能重复和冲突
|
||||
|
||||
## 📋 重要文档引用
|
||||
|
||||
**开始前请查看**: `essential_docs.md` 获取所有必读文档清单,特别是:
|
||||
- `../../协作机制设计.md` - 了解模块间如何协作
|
||||
- `../../模块分工指南.md` - 明确各模块的职责边界
|
||||
- `../../开发规范文档.md` - 详细的编码规范
|
||||
|
||||
### 🔧 配置管理文档
|
||||
**重要**:以下两个文档用于确保系统配置一致性,避免常见配置错误:
|
||||
|
||||
- **`../../配置一致性检查清单.md`** - 记录所有需要保持一致的配置项
|
||||
- **何时查看**:遇到数据库连接、CORS、认证等问题时必须查看
|
||||
- **何时更新**:添加新配置项或修改现有配置时必须更新
|
||||
|
||||
- **`../../配置管理使用说明.md`** - 配置管理工具的使用指南
|
||||
- **何时查看**:第一次开发时、遇到配置问题时、需要部署新环境时
|
||||
- **何时更新**:发现新的配置问题解决方案或改进工具时更新
|
||||
|
||||
**配置检查脚本**:项目根目录的 `../../../check-config.sh` 可自动检查配置一致性
|
||||
|
||||
## 项目背景
|
||||
|
||||
考培练系统是一个革命性的员工能力提升平台,通过集成Coze和Dify双AI平台,实现智能化的培训、考核和陪练功能。系统采用Python FastAPI作为后端框架,前端使用Vue3。
|
||||
|
||||
## 技术栈
|
||||
- **后端框架**: Python 3.8+ + FastAPI
|
||||
- **数据库**: MySQL 8.0 + Redis
|
||||
- **ORM**: SQLAlchemy 2.0
|
||||
- **AI平台**: Coze(陪练和对话) + Dify(考试和评估)
|
||||
- **认证**: JWT
|
||||
- **部署**: Docker
|
||||
|
||||
## 🔧 开发规范
|
||||
|
||||
### 代码质量标准
|
||||
1. **类型注解**:所有Python函数必须有完整的类型注解
|
||||
2. **错误处理**:使用统一的异常处理机制,避免裸露的try-except
|
||||
3. **日志记录**:使用structlog记录关键操作和错误信息
|
||||
4. **测试覆盖**:为核心业务逻辑编写单元测试,覆盖率必须达到80%以上
|
||||
5. **文档注释**:使用中文注释,遵循Google风格
|
||||
|
||||
### 架构遵循
|
||||
1. **分层架构**:严格按照Controller -> Service -> Repository -> Model层次
|
||||
2. **依赖注入**:使用FastAPI的Depends机制管理依赖
|
||||
3. **数据验证**:使用Pydantic模型进行数据验证和序列化
|
||||
4. **异步编程**:数据库操作必须使用async/await
|
||||
|
||||
### 代码规范示例
|
||||
```python
|
||||
# 导入顺序:标准库 -> 第三方库 -> 本地模块
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
# 使用类型注解
|
||||
async def get_user_by_id(
|
||||
user_id: int,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
) -> Optional[User]:
|
||||
"""
|
||||
根据ID获取用户
|
||||
|
||||
Args:
|
||||
user_id: 用户ID
|
||||
db: 数据库会话
|
||||
|
||||
Returns:
|
||||
User对象或None
|
||||
"""
|
||||
# 实现代码
|
||||
pass
|
||||
```
|
||||
|
||||
## 🛠️ 调试问题的系统化方法
|
||||
|
||||
### 问题定位策略(按优先级)
|
||||
|
||||
#### 1. **分层验证法**
|
||||
```
|
||||
第一层:数据库连接和查询是否正常
|
||||
第二层:业务逻辑服务是否正确
|
||||
第三层:API接口是否正常响应
|
||||
第四层:前端调用是否成功
|
||||
```
|
||||
|
||||
#### 2. **配置一致性检查**
|
||||
**在解决任何问题前,必须先运行配置检查**:
|
||||
```bash
|
||||
cd ../../../
|
||||
./check-config.sh
|
||||
```
|
||||
|
||||
检查清单:
|
||||
- [ ] 数据库连接字符串(用户名/密码/端口)
|
||||
- [ ] CORS域名配置(前端端口是否在允许列表中)
|
||||
- [ ] API请求/响应格式(JSON vs form-data)
|
||||
- [ ] 环境变量与默认值一致性
|
||||
- [ ] 认证token的存储键名统一性
|
||||
|
||||
#### 3. **错误信息分类处理**
|
||||
```python
|
||||
# 500错误 -> 重点检查:
|
||||
- 数据库连接配置
|
||||
- 环境变量加载
|
||||
- 代码语法错误
|
||||
|
||||
# 400/422错误 -> 重点检查:
|
||||
- 请求参数格式
|
||||
- Pydantic模型验证
|
||||
- 必填字段缺失
|
||||
|
||||
# 401/403错误 -> 重点检查:
|
||||
- JWT token生成/验证
|
||||
- 权限控制逻辑
|
||||
- 认证状态管理
|
||||
|
||||
# CORS错误 -> 重点检查:
|
||||
- 前端运行端口
|
||||
- 后端CORS配置
|
||||
- 请求头设置
|
||||
```
|
||||
|
||||
### 调试工具使用
|
||||
1. **后端调试**:
|
||||
```bash
|
||||
# 直接测试API
|
||||
curl -X POST http://localhost:8000/api/v1/endpoint \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"key": "value"}'
|
||||
|
||||
# 检查服务健康状态
|
||||
curl http://localhost:8000/health
|
||||
```
|
||||
|
||||
2. **前端调试**:
|
||||
- 使用浏览器开发者工具监控网络请求
|
||||
- 检查localStorage/sessionStorage数据
|
||||
- 查看控制台错误和警告信息
|
||||
|
||||
3. **数据库调试**:
|
||||
```bash
|
||||
# 检查Docker服务状态
|
||||
docker-compose ps
|
||||
|
||||
# 连接数据库验证
|
||||
docker exec -it mysql mysql -uroot -proot -e "SHOW DATABASES;"
|
||||
```
|
||||
|
||||
## 🔐 认证授权开发规范
|
||||
|
||||
### 统一认证流程
|
||||
1. **后端**:
|
||||
```python
|
||||
# 使用统一的JWT工具
|
||||
from app.core.security import create_tokens, verify_token
|
||||
|
||||
# 使用统一的依赖注入
|
||||
from app.core.deps import get_current_user, require_admin
|
||||
```
|
||||
|
||||
2. **前端**:
|
||||
```typescript
|
||||
// 使用统一的认证管理器
|
||||
import { authManager } from '@/utils/auth'
|
||||
|
||||
// 统一的token存储
|
||||
authManager.setAccessToken(token)
|
||||
authManager.setCurrentUser(user)
|
||||
```
|
||||
|
||||
### 权限控制模式
|
||||
```python
|
||||
# 路由级权限控制
|
||||
@router.get("/admin-only")
|
||||
async def admin_endpoint(
|
||||
current_user: User = Depends(require_admin)
|
||||
):
|
||||
pass
|
||||
|
||||
# 业务逻辑权限控制
|
||||
if not current_user.has_permission("resource:action"):
|
||||
raise InsufficientPermissionsError()
|
||||
```
|
||||
|
||||
## 📡 API开发规范
|
||||
|
||||
### 统一响应格式
|
||||
```python
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
@router.post("/endpoint", response_model=ResponseModel[DataSchema])
|
||||
async def endpoint():
|
||||
return ResponseModel(
|
||||
data=result,
|
||||
message="操作成功"
|
||||
)
|
||||
```
|
||||
|
||||
### 标准响应格式
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
// 实际数据
|
||||
},
|
||||
"request_id": "uuid"
|
||||
}
|
||||
```
|
||||
|
||||
### 错误处理模式
|
||||
使用项目统一的异常类:
|
||||
- BadRequestError (400)
|
||||
- UnauthorizedError (401)
|
||||
- ForbiddenError (403)
|
||||
- NotFoundError (404)
|
||||
- ConflictError (409)
|
||||
- ValidationError (422)
|
||||
- InternalServerError (500)
|
||||
|
||||
```python
|
||||
try:
|
||||
result = await service.do_something()
|
||||
return ResponseModel(data=result)
|
||||
except BusinessError as e:
|
||||
raise HTTPException(
|
||||
status_code=e.code,
|
||||
detail={"message": e.message, "error_code": e.error_code}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("操作失败", error=str(e), exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail={"message": "内部服务器错误"}
|
||||
)
|
||||
```
|
||||
|
||||
## 🗄️ 数据库开发规范
|
||||
|
||||
### 模型定义
|
||||
```python
|
||||
from app.models.base import BaseModel
|
||||
|
||||
class YourModel(BaseModel):
|
||||
__tablename__ = "your_table"
|
||||
|
||||
# 字段定义使用完整类型注解
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
```
|
||||
|
||||
### 数据库操作要求
|
||||
- 使用异步ORM操作
|
||||
- 所有表必须继承BaseModel
|
||||
- 软删除使用SoftDeleteMixin
|
||||
- 审计字段使用AuditMixin
|
||||
|
||||
```python
|
||||
# 使用异步会话
|
||||
async def get_by_id(db: AsyncSession, id: int) -> Optional[Model]:
|
||||
result = await db.execute(
|
||||
select(Model).where(Model.id == id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
```
|
||||
|
||||
## 🧪 测试开发规范
|
||||
|
||||
### 单元测试
|
||||
```python
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint(client: AsyncClient, test_user):
|
||||
response = await client.post(
|
||||
"/api/v1/endpoint",
|
||||
json={"key": "value"},
|
||||
headers={"Authorization": f"Bearer {test_user.token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["code"] == 200
|
||||
```
|
||||
|
||||
## 📝 日志记录规范
|
||||
```python
|
||||
from app.core.logger import logger
|
||||
|
||||
# 记录重要操作
|
||||
logger.info("用户登录成功", user_id=user.id, username=user.username)
|
||||
|
||||
# 记录错误
|
||||
logger.error("数据库连接失败", error=str(e), exc_info=True)
|
||||
```
|
||||
|
||||
## 🚨 常见陷阱避免
|
||||
|
||||
### 配置相关
|
||||
- ❌ 不要假设环境变量已正确加载,要检查默认值
|
||||
- ❌ 不要忽略CORS配置,特别是开发环境的多端口问题
|
||||
- ❌ 不要混用不同的数据格式(JSON vs form-urlencoded)
|
||||
|
||||
### 认证相关
|
||||
- ❌ 不要手动管理认证状态,要使用统一的authManager
|
||||
- ❌ 不要在localStorage中使用随意的键名
|
||||
- ❌ 不要忘记在API请求中自动添加Authorization头
|
||||
|
||||
### 开发相关
|
||||
- ❌ 不要直接使用裸露的SQL查询
|
||||
- ❌ 不要忘记异步函数的await关键字
|
||||
- ❌ 不要在生产代码中留下调试信息
|
||||
|
||||
## 📝 协作规范
|
||||
|
||||
### 与其他子agent的协作
|
||||
1. **接口约定**:严格按照API文档定义接口
|
||||
2. **数据模型**:共享的数据模型要在base模块中定义
|
||||
3. **工具函数**:通用工具函数放在utils模块
|
||||
4. **配置管理**:统一使用settings模块管理配置
|
||||
|
||||
### 代码提交规范
|
||||
```bash
|
||||
# 提交格式
|
||||
git commit -m "feat(module): 添加用户管理功能"
|
||||
git commit -m "fix(auth): 修复登录状态不同步问题"
|
||||
git commit -m "docs(api): 更新API文档"
|
||||
```
|
||||
|
||||
## 🔄 持续改进
|
||||
|
||||
### 问题反馈机制
|
||||
当遇到新的问题或发现更好的解决方案时:
|
||||
1. 更新相关文档(如配置一致性检查清单)
|
||||
2. 分享经验给其他子agent
|
||||
3. 完善错误处理和日志记录
|
||||
|
||||
### 代码审查要点
|
||||
1. 配置一致性检查
|
||||
2. 错误处理完整性
|
||||
3. 安全性验证
|
||||
4. 性能优化机会
|
||||
5. 代码可读性和维护性
|
||||
|
||||
## 🎯 集成经验总结(来自Agent-User)
|
||||
|
||||
### SQLAlchemy兼容性问题
|
||||
**问题**:SQLAlchemy 2.0对类型注解有严格要求,可能出现`Type annotation can't be correctly interpreted`错误。
|
||||
|
||||
**解决方案**:
|
||||
```python
|
||||
# 在模型类中添加
|
||||
class MyModel(BaseModel):
|
||||
__allow_unmapped__ = True
|
||||
__tablename__ = "my_table"
|
||||
```
|
||||
|
||||
### Python环境问题
|
||||
**问题**:macOS系统可能出现`externally-managed-environment`错误。
|
||||
|
||||
**解决方案**:
|
||||
```bash
|
||||
# 使用--break-system-packages
|
||||
pip install --break-system-packages -r requirements/dev.txt
|
||||
|
||||
# 或使用用户安装
|
||||
pip install --user package_name
|
||||
|
||||
# 工具可能在~/.local/bin/
|
||||
~/.local/bin/black app/ tests/
|
||||
```
|
||||
|
||||
### 数据库迁移备选方案
|
||||
如果Alembic迁移失败,准备手动SQL脚本:
|
||||
```sql
|
||||
-- scripts/manual_db_init.sql
|
||||
CREATE TABLE IF NOT EXISTS your_table (...);
|
||||
```
|
||||
|
||||
### 集成验证步骤
|
||||
1. 清理所有测试文件
|
||||
2. 安装依赖(包括dev依赖)
|
||||
3. 运行数据库迁移或手动SQL
|
||||
4. 创建测试数据
|
||||
5. 验证API端点
|
||||
6. 更新相关文档
|
||||
|
||||
### 端口冲突处理
|
||||
```bash
|
||||
# 检查端口占用
|
||||
lsof -i :8000
|
||||
|
||||
# 清理相关进程
|
||||
pkill -f uvicorn
|
||||
```
|
||||
|
||||
## ✅ 提交前检查清单
|
||||
- [ ] 代码通过 `make format` 格式化
|
||||
- [ ] 代码通过 `make lint` 检查
|
||||
- [ ] 代码通过 `make type-check` 类型检查
|
||||
- [ ] 编写了相应的测试用例
|
||||
- [ ] 测试通过 `make test`
|
||||
- [ ] 运行配置检查脚本 `../../../check-config.sh`
|
||||
- [ ] 更新了相关文档
|
||||
|
||||
---
|
||||
|
||||
**核心原则**:配置一致性是分布式系统的生命线,任何一个配置不匹配都可能导致整个系统无法工作。在开发过程中,始终优先检查配置一致性!
|
||||
98
docs/规划/后端开发拆分策略/子agent/00-通用基础/essential_docs.md
Normal file
98
docs/规划/后端开发拆分策略/子agent/00-通用基础/essential_docs.md
Normal file
@@ -0,0 +1,98 @@
|
||||
# 必读文档清单
|
||||
|
||||
## 核心规划文档
|
||||
|
||||
这些文档包含了项目的重要设计决策,所有Agent都应该了解:
|
||||
|
||||
### 1. 架构设计文档
|
||||
|
||||
- `../../协作机制设计.md` - **必读** - 模块间协作机制、全局上下文、错误处理
|
||||
- `../../项目脚手架结构.md` - **必读** - 详细的目录结构和文件组织
|
||||
- `../../模块分工指南.md` - **必读** - 各模块的职责边界和接口定义
|
||||
- `../../开发规范文档.md` - **必读** - 详细的编码规范和最佳实践
|
||||
|
||||
### 2. 业务理解文档
|
||||
|
||||
- `../../../README.md` - 项目整体介绍
|
||||
- `../../../../kaopeilian-frontend/页面与按钮速查.md` - 前端页面框架和功能
|
||||
- `../../../../kaopeilian-frontend/前后端接口约定.md` - 前后端接口约定
|
||||
|
||||
### 3. 质量保证文档
|
||||
|
||||
- `../../质量保证机制.md` - 代码审查和测试要求
|
||||
- `../../统一基础代码.md` - 可复用的代码模板
|
||||
|
||||
### 4. 配置管理文档
|
||||
|
||||
- `../../配置一致性检查清单.md` - **必读** - 所有需要保持一致的配置项清单
|
||||
- `../../配置管理使用说明.md` - **必读** - 配置管理工具使用指南和最佳实践
|
||||
|
||||
## 使用建议
|
||||
|
||||
### 对于每个Agent
|
||||
|
||||
1. **开发前必读**:
|
||||
|
||||
- 本目录的 `base_prompt.md`
|
||||
- 本目录的 `project_structure.md`
|
||||
- `../../协作机制设计.md`
|
||||
- `../../模块分工指南.md`
|
||||
- `../../配置一致性检查清单.md`
|
||||
|
||||
2. **开发中参考**:
|
||||
|
||||
- `../../开发规范文档.md`
|
||||
- `../../统一基础代码.md`
|
||||
- `../../配置管理使用说明.md`
|
||||
- 相关模块的接口定义
|
||||
|
||||
3. **遇到问题时**:
|
||||
|
||||
- 先运行配置检查脚本:`../../../../../check-config.sh`
|
||||
- 查看 `../../配置一致性检查清单.md`
|
||||
- 参考 `../../配置管理使用说明.md`
|
||||
|
||||
4. **集成时查看**:
|
||||
|
||||
- 依赖模块的API契约
|
||||
- `../../质量保证机制.md`
|
||||
|
||||
### 文档引用示例
|
||||
|
||||
```markdown
|
||||
# 在对话中引用
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
|
||||
我已了解项目的协作机制和模块分工,开始开发Auth模块。
|
||||
```
|
||||
|
||||
## 重要提醒
|
||||
|
||||
- 这些文档包含了项目的核心设计理念
|
||||
- 遵循这些文档可以确保代码的一致性
|
||||
- 有疑问时优先查阅这些文档而不是自行决定
|
||||
- 禁止在各模块文档中重复粘贴通用规范,统一通过本目录进行引用,避免信息漂移
|
||||
|
||||
## 可复用资产索引(Coze 并入)
|
||||
- 代码位置
|
||||
- 后端(完整可并入):`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-backend/`
|
||||
- 关键文件:`auth.py`(OAuth/JWT 优先,PAT 回退,直连 *.coze.cn)、`main.py`(SSE/卡片/会话/上传/中断)、`config.py`/`local_config.py`(本地/环境配置)。
|
||||
- 目标映射:
|
||||
- → `kaopeilian-backend/app/services/ai/coze/{client.py,service.py,exceptions.py,models.py}`
|
||||
- → `kaopeilian-backend/app/api/v1/coze_gateway.py`
|
||||
- 前端(可快速接入或重写):`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-frontend/`
|
||||
- 页面:`src/pages/{NewChat,Exam,Training}`
|
||||
- Store:`src/stores/{NewChatStore,ExamStore,TrainingStore}.ts`
|
||||
- API:`src/server/{api.ts,global.ts}`(SSE/中断/上传)
|
||||
- 目标策略:
|
||||
- 快速:以子应用挂载 `/ai-chat/*`;
|
||||
- 稳定:迁移为 Vue3 + Pinia,复用 SSE/卡片渲染逻辑。
|
||||
- 配置项(本地/环境变量)
|
||||
- `COZE_API_BASE`、`COZE_WORKSPACE_ID`、`COZE_API_TOKEN`
|
||||
- `COZE_OAUTH_CLIENT_ID`、`COZE_OAUTH_PUBLIC_KEY_ID`、`COZE_OAUTH_PRIVATE_KEY_PATH`
|
||||
- 建议:生产关闭“开发用 PAT 获取”,统一 `Bearer` 鉴权,设置 `NO_PROXY=localhost,127.0.0.1,api.coze.cn,.coze.cn`。
|
||||
- 参考说明
|
||||
- 根目录:`配置说明.md`、`README.md`(已含运行与映射说明)
|
||||
- 并入后务必以各模块 `api_contract.yaml` 为准,旧路由通过网关短期兼容,按里程碑收敛。
|
||||
731
docs/规划/后端开发拆分策略/子agent/00-通用基础/integration_experience.md
Normal file
731
docs/规划/后端开发拆分策略/子agent/00-通用基础/integration_experience.md
Normal file
@@ -0,0 +1,731 @@
|
||||
# 子Agent集成经验总结
|
||||
|
||||
## Agent-Coze 集成经验(2025-09-21)
|
||||
|
||||
项目数据库:
|
||||
|
||||
1、数据库初始化SQL脚本:/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/scripts/init_database_unified.sql
|
||||
|
||||
2、数据库架构:/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/数据库架构-统一版.md
|
||||
|
||||
|
||||
### 遇到的问题及解决方案
|
||||
|
||||
1. **配置文件路径不一致**
|
||||
|
||||
- 问题:项目中存在两个配置文件(app/config/settings.py 和 app/core/config.py)
|
||||
- 解决:统一使用 app.core.config,修复所有导入路径
|
||||
2. **Pydantic 验证错误**
|
||||
|
||||
- 问题:Settings 模型没有设置 extra="allow",导致环境变量验证失败
|
||||
- 解决:在 SettingsConfigDict 中添加 extra="allow"
|
||||
3. **数据库连接池配置**
|
||||
|
||||
- 问题:使用 NullPool 时不能指定 pool_size 和 max_overflow 参数
|
||||
- 解决:根据 DEBUG 模式分别配置,开发环境使用 NullPool,生产环境使用连接池
|
||||
4. **缺失的依赖注入函数**
|
||||
|
||||
- 问题:多个模块导入了不存在的函数(get_current_active_user, get_redis 等)
|
||||
- 解决:在 deps.py 中添加缺失的函数实现
|
||||
5. **缺失的 Pydantic 模型**
|
||||
|
||||
- 问题:PaginatedResponse 和 PaginationParams 未定义
|
||||
- 解决:在 schemas/base.py 中添加这些模型定义
|
||||
|
||||
### 集成步骤总结
|
||||
|
||||
1. 配置环境变量(.env 文件)
|
||||
2. 复制私钥文件到正确位置
|
||||
3. 替换临时的 Coze 客户端为真实实现
|
||||
4. 修复所有导入和配置问题
|
||||
5. 创建前端页面并集成 API 调用
|
||||
6. 测试端点可用性
|
||||
|
||||
### 建议
|
||||
|
||||
1. 子agent开发时应提供完整的代码实现,避免只有接口定义
|
||||
2. 统一项目的配置管理方式,避免多个配置文件
|
||||
3. 提供更详细的依赖关系文档,包括需要的模型和函数
|
||||
4. 使用类型注解和 mypy 检查,提前发现导入问题
|
||||
|
||||
## 来自Agent-User的集成经验
|
||||
|
||||
### 1. 遇到的主要问题
|
||||
|
||||
#### 1.1 SQLAlchemy版本兼容性问题
|
||||
|
||||
**问题描述**:
|
||||
|
||||
- SQLAlchemy 2.0对类型注解有严格要求
|
||||
- 使用 `Mapped[]`类型注解的模型与使用传统 `Column`定义的Mixin不兼容
|
||||
- 错误信息:`Type annotation for "User.created_at" can't be correctly interpreted`
|
||||
|
||||
**解决方案**:
|
||||
|
||||
```python
|
||||
# 在Base类和BaseModel类中添加
|
||||
__allow_unmapped__ = True
|
||||
```
|
||||
|
||||
**建议**:
|
||||
|
||||
- 新开发的子Agent应该统一使用SQLAlchemy 2.0的新式声明方式
|
||||
- 或者在基础模型中预先添加 `__allow_unmapped__ = True`
|
||||
|
||||
#### 1.2 Python环境依赖问题
|
||||
|
||||
**问题描述**:
|
||||
|
||||
- macOS系统Python环境的"externally-managed-environment"限制
|
||||
- 无法直接使用pip安装包到系统Python
|
||||
|
||||
**解决方案**:
|
||||
|
||||
- 使用 `--break-system-packages`标志
|
||||
- 或安装到用户目录:`pip install --user`
|
||||
- 使用完整路径调用工具:`~/.local/bin/black`
|
||||
|
||||
#### 1.3 数据库连接问题
|
||||
|
||||
**问题描述**:
|
||||
|
||||
- MySQL密码认证失败
|
||||
- Alembic迁移执行失败
|
||||
|
||||
**解决方案**:
|
||||
|
||||
- 创建手动SQL脚本作为备选方案
|
||||
- 使用pymysql代替aiomysql进行迁移
|
||||
- 确保.env文件中的数据库配置正确
|
||||
|
||||
### 2. 集成最佳实践
|
||||
|
||||
#### 2.1 文件清理
|
||||
|
||||
- 删除所有测试文件(test_server.py、demo_app.py等)
|
||||
- 删除临时数据库文件(*.db)
|
||||
- 清理测试脚本
|
||||
|
||||
#### 2.2 依赖管理
|
||||
|
||||
```bash
|
||||
# 安装所有依赖,包括dev依赖
|
||||
pip install --break-system-packages -r requirements/dev.txt
|
||||
```
|
||||
|
||||
#### 2.3 数据库初始化
|
||||
|
||||
1. 优先使用Alembic迁移
|
||||
2. 如果失败,使用手动SQL脚本
|
||||
3. 创建测试数据验证
|
||||
|
||||
#### 2.4 服务验证
|
||||
|
||||
- 使用多种方式验证服务是否正常运行
|
||||
- 检查端口占用情况
|
||||
- 查看进程状态
|
||||
|
||||
### 3. 子Agent开发建议
|
||||
|
||||
#### 3.1 模型定义
|
||||
|
||||
```python
|
||||
# 推荐:统一使用SQLAlchemy 2.0风格
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
class MyModel(BaseModel):
|
||||
__tablename__ = "my_table"
|
||||
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
```
|
||||
|
||||
#### 3.2 错误处理
|
||||
|
||||
- 预期可能的兼容性问题
|
||||
- 准备多种解决方案
|
||||
- 记录详细的错误信息
|
||||
|
||||
#### 3.3 测试策略
|
||||
|
||||
- 先创建简单的测试脚本验证功能
|
||||
- 逐步集成到主系统
|
||||
- 保留手动SQL作为备选方案
|
||||
|
||||
### 4. 提示词优化建议
|
||||
|
||||
为下一个子Agent添加以下提示:
|
||||
|
||||
1. **SQLAlchemy兼容性警告**:
|
||||
|
||||
- 如果遇到类型注解错误,在模型类中添加 `__allow_unmapped__ = True`
|
||||
- 统一使用SQLAlchemy 2.0的声明方式
|
||||
2. **环境配置提醒**:
|
||||
|
||||
- macOS可能需要使用 `--break-system-packages`
|
||||
- 工具可能安装在 `~/.local/bin/`
|
||||
3. **数据库迁移备选**:
|
||||
|
||||
- 准备手动SQL脚本作为Alembic失败的备选方案
|
||||
- 测试时可以使用SQLite快速验证
|
||||
4. **集成验证清单**:
|
||||
|
||||
- 清理测试文件
|
||||
- 安装依赖
|
||||
- 数据库迁移
|
||||
- 创建测试数据
|
||||
- API验证
|
||||
- 更新文档
|
||||
|
||||
### 5. 通用解决方案模板
|
||||
|
||||
```python
|
||||
# 1. 模型定义模板
|
||||
class MyModel(BaseModel):
|
||||
__tablename__ = "my_table"
|
||||
__allow_unmapped__ = True # 添加兼容性支持
|
||||
|
||||
# 使用Mapped类型注解
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
|
||||
# 2. 服务启动检查
|
||||
import os
|
||||
os.system("lsof -i :8000") # 检查端口
|
||||
os.system("pkill -f uvicorn") # 清理进程
|
||||
|
||||
# 3. 数据库初始化备选
|
||||
if alembic_fails:
|
||||
execute_manual_sql_script()
|
||||
```
|
||||
|
||||
### 6. 前端集成经验总结(来自Agent-User)
|
||||
|
||||
#### 前端模拟数据到后端服务的切换
|
||||
|
||||
1. **环境配置优先级**
|
||||
|
||||
- 前端 `.env`文件优先级最高,覆盖所有默认配置
|
||||
- 确保 `VITE_USE_MOCK_DATA=false`禁用模拟数据模式
|
||||
- 正确设置 `VITE_API_BASE_URL=http://localhost:8000`
|
||||
2. **API接口匹配**
|
||||
|
||||
- 前端期望的响应格式必须与后端返回格式完全匹配
|
||||
- 登录响应:前端期望 `data.token.access_token`,后端返回 `data.token.access_token`
|
||||
- 刷新令牌:前端调用时需要传递 `refresh_token`参数
|
||||
- 用户信息:前端调用 `/api/v1/users/me`,后端提供 `/api/v1/users/me`
|
||||
3. **依赖管理**
|
||||
|
||||
```bash
|
||||
# 修复vite.config.ts中的rollup-plugin-visualizer条件导入
|
||||
# 错误写法:
|
||||
process.env.ANALYZE === 'true' && visualizer({...})
|
||||
|
||||
# 正确写法:
|
||||
...(process.env.ANALYZE === 'true' ? [visualizer({...})] : [])
|
||||
```
|
||||
4. **代理配置验证**
|
||||
|
||||
- 前端Vite配置中的代理必须正确指向后端
|
||||
- 代理路径:`/api` → `http://localhost:8000`
|
||||
- 确保代理配置不影响真实API调用
|
||||
5. **测试策略**
|
||||
|
||||
- 先单独测试后端API,确保功能正常
|
||||
- 再测试前端代理,确保代理配置正确
|
||||
- 最后进行完整的前后端集成测试
|
||||
6. **调试技巧**
|
||||
|
||||
- 使用 `curl`命令直接测试API端点
|
||||
- 检查浏览器网络面板,确认请求路径和响应格式
|
||||
- 使用 `lsof -i :8000`检查端口占用情况
|
||||
- 使用 `ps aux | grep python3`检查进程状态
|
||||
|
||||
### 7. 注意事项
|
||||
|
||||
1. **不要过度演示**:专注于实际集成,而不是创建演示应用
|
||||
2. **保持代码整洁**:及时清理测试文件和临时文件
|
||||
3. **文档同步**:完成开发后立即更新相关文档
|
||||
4. **经验传承**:将遇到的问题和解决方案记录下来
|
||||
|
||||
### 8. 03-course Agent集成经验(2025-09-21)
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **导入名称不匹配问题**
|
||||
|
||||
- 问题:`PageParams`和 `PageResult`与 `PaginationParams`和 `PaginatedResponse`名称不一致
|
||||
- 解决:全局替换所有相关导入和使用
|
||||
- 建议:子Agent开发时要确保使用统一的基础组件命名
|
||||
2. **服务启动困难**
|
||||
|
||||
- 问题:uvicorn服务启动时端口占用,进程管理混乱
|
||||
- 解决:使用 `lsof -i :8000`查找占用进程,`kill -9`强制停止
|
||||
- 建议:提供更稳定的服务启动脚本
|
||||
3. **模型导入缺失**
|
||||
|
||||
- 问题:`DateTime`类型未从SQLAlchemy导入
|
||||
- 解决:在导入语句中添加 `DateTime`
|
||||
- 建议:子Agent开发时仔细检查所有必需的导入
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **手动SQL脚本备份**
|
||||
|
||||
- 当Alembic迁移失败时,手动SQL脚本是很好的备选方案
|
||||
- 脚本中包含了测试数据,方便快速验证
|
||||
2. **清晰的集成清单**
|
||||
|
||||
- 使用TODO清单系统化管理集成步骤
|
||||
- 每完成一步立即更新状态,保持进度可见
|
||||
3. **文档同步更新**
|
||||
|
||||
- 在集成过程中同步更新README和数据库架构文档
|
||||
- 确保文档与代码保持一致
|
||||
|
||||
这些经验将帮助后续的子Agent开发更加顺畅,减少重复踩坑。
|
||||
|
||||
### 14. 05-training Agent集成经验(2025-09-21)
|
||||
|
||||
#### 集成概况
|
||||
|
||||
05-training子agent集成顺利完成,主要涉及:
|
||||
1. 新增4个training相关数据库表
|
||||
2. 完整的training API端点实现
|
||||
3. 前后端完整对接验证
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **SQLAlchemy模型字段冲突**
|
||||
- 问题:`TrainingMessage`模型中使用`metadata`字段名与SQLAlchemy保留字冲突
|
||||
- 解决:重命名为`message_metadata`字段
|
||||
- 建议:避免使用SQLAlchemy保留字作为字段名
|
||||
|
||||
2. **CozeClient导入错误**
|
||||
- 问题:`app/services/training_service.py`中导入不存在的`CozeClient`类
|
||||
- 解决:注释掉导入语句,使用模拟模式
|
||||
- 建议:子Agent开发时确保所有导入的类都存在或提供mock实现
|
||||
|
||||
3. **路由重复前缀问题**
|
||||
- 问题:`training.py`中定义了`prefix="/training"`,在`__init__.py`中又添加了前缀
|
||||
- 解决:移除`training.py`中的重复前缀定义
|
||||
- 建议:统一在路由注册时添加前缀
|
||||
|
||||
4. **数据库迁移执行问题**
|
||||
- 问题:Alembic自动迁移遇到外键类型不匹配
|
||||
- 解决:使用手动SQL脚本创建training表
|
||||
- 建议:复杂表结构优先使用手动SQL脚本
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **完整的API实现**
|
||||
- 实现了场景管理、会话管理、消息管理、报告管理的完整API
|
||||
- 支持分页查询、权限控制、数据验证
|
||||
- API响应格式统一,错误处理完善
|
||||
|
||||
2. **数据库设计合理**
|
||||
- training_scenes: 陪练场景配置
|
||||
- training_sessions: 会话管理和状态跟踪
|
||||
- training_messages: 消息记录和语音支持
|
||||
- training_reports: 智能分析报告
|
||||
|
||||
3. **代码质量保证**
|
||||
- 使用black格式化了27个文件
|
||||
- 修复了所有导入和类型问题
|
||||
- 保持了代码的一致性和可读性
|
||||
|
||||
#### 验证清单
|
||||
|
||||
- [x] 配置检查与修复:.env文件、数据库配置、Python依赖
|
||||
- [x] 数据库迁移:手动SQL脚本创建training表
|
||||
- [x] 服务启动:MySQL/Redis正常,后端服务成功启动
|
||||
- [x] 后端API验证:健康检查、API文档、training端点正常
|
||||
- [x] 前后端对接验证:CORS配置正确,前端页面正常显示
|
||||
- [x] 测试验证:代码格式化完成,修复导入错误
|
||||
- [x] 文档更新:数据库架构文档已包含training表结构
|
||||
|
||||
#### API端点验证
|
||||
|
||||
新增的training API端点:
|
||||
- `GET /api/v1/training/scenes` - 获取陪练场景列表
|
||||
- `GET /api/v1/training/scenes/{scene_id}` - 获取场景详情
|
||||
- `POST /api/v1/training/scenes` - 创建场景(管理员)
|
||||
- `PUT /api/v1/training/scenes/{scene_id}` - 更新场景(管理员)
|
||||
- `DELETE /api/v1/training/scenes/{scene_id}` - 删除场景(管理员)
|
||||
- `POST /api/v1/training/sessions` - 开始陪练会话
|
||||
- `POST /api/v1/training/sessions/{session_id}/end` - 结束会话
|
||||
- `GET /api/v1/training/sessions` - 获取用户会话列表
|
||||
- `GET /api/v1/training/sessions/{session_id}` - 获取会话详情
|
||||
- `GET /api/v1/training/sessions/{session_id}/messages` - 获取会话消息
|
||||
- `GET /api/v1/training/reports` - 获取用户报告列表
|
||||
- `GET /api/v1/training/reports/{report_id}` - 获取报告详情
|
||||
- `GET /api/v1/training/sessions/{session_id}/report` - 获取会话报告
|
||||
|
||||
#### 注意事项
|
||||
|
||||
1. **Coze集成准备**
|
||||
- training模块已预留Coze Bot集成接口
|
||||
- 当Coze客户端实现后,可以直接启用AI陪练功能
|
||||
- 目前使用模拟模式,不影响基础功能
|
||||
|
||||
2. **数据库表设计**
|
||||
- training表已包含软删除字段
|
||||
- 支持JSON配置和元数据存储
|
||||
- 外键关系完整,支持级联删除
|
||||
|
||||
3. **权限控制**
|
||||
- 场景管理需要管理员权限
|
||||
- 会话和报告支持用户权限隔离
|
||||
- API支持角色验证和数据过滤
|
||||
|
||||
4. **扩展性考虑**
|
||||
- 支持语音消息和实时通信
|
||||
- 预留WebSocket连接地址
|
||||
- 支持多维度评分和智能分析
|
||||
|
||||
这次集成非常成功,05-training的功能已完全集成到系统中,为用户提供了完整的AI陪练功能框架。
|
||||
|
||||
### 13. 06-Agent-Analytics集成经验(2025-09-21)
|
||||
|
||||
#### 集成概况
|
||||
|
||||
06-Agent-Analytics子agent集成相对顺利,主要是因为:
|
||||
1. 没有新增数据库模型,避免了数据库迁移问题
|
||||
2. 主要是对现有数据的统计分析功能
|
||||
3. 基础设施已经完善,集成流程标准化
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **配置文件LOG_LEVEL属性访问错误**
|
||||
- 问题:`app/core/logger.py`中使用`settings.log_level`而不是`settings.LOG_LEVEL`
|
||||
- 解决:修改logger.py中的属性访问,统一使用大写形式
|
||||
- 建议:确保配置属性命名的一致性
|
||||
|
||||
2. **测试文件导入错误**
|
||||
- 问题:`app/schemas/training.py`中缺少`Generic`和`TypeVar`导入
|
||||
- 解决:添加必要的typing导入并定义`DataT = TypeVar('DataT')`
|
||||
- 建议:子Agent开发时确保所有类型注解的导入完整
|
||||
|
||||
3. **服务启动端口占用**
|
||||
- 问题:8000端口被之前的进程占用
|
||||
- 解决:使用`pkill -f "uvicorn"`清理进程后重新启动
|
||||
- 建议:开发脚本中加入端口清理逻辑
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **标准化集成流程**
|
||||
- 使用TODO清单系统化管理集成步骤
|
||||
- 每个步骤完成后立即更新状态
|
||||
- 保持集成过程的可追踪性
|
||||
|
||||
2. **完善的验证体系**
|
||||
- 后端API健康检查:`/health`端点正常响应
|
||||
- API文档可访问:`http://localhost:8000/docs`
|
||||
- 前后端对接正常:CORS配置正确,前端页面正常显示
|
||||
- 认证流程完整:登录API返回正确的token格式
|
||||
|
||||
3. **代码质量保证**
|
||||
- 使用black进行代码格式化,处理了27个文件
|
||||
- 修复了导入错误和类型注解问题
|
||||
- 保持了代码的一致性和可读性
|
||||
|
||||
#### 验证清单
|
||||
|
||||
- [x] 配置检查与修复:.env文件、数据库配置、Python依赖
|
||||
- [x] 数据库迁移:无新模型,跳过迁移步骤
|
||||
- [x] 服务启动:MySQL/Redis正常,后端服务成功启动
|
||||
- [x] 后端API验证:健康检查、API文档、测试端点正常
|
||||
- [x] 前后端对接验证:CORS配置正确,前端页面正常显示
|
||||
- [x] 测试验证:代码格式化完成,修复导入错误
|
||||
- [x] 文档更新:无需更新,Analytics功能已在现有架构中
|
||||
|
||||
#### API端点验证
|
||||
|
||||
当前系统提供的API端点:
|
||||
- `GET /health` - 健康检查
|
||||
- `GET /` - 根路径信息
|
||||
- `POST /api/v1/chat/messages` - 聊天消息
|
||||
- `GET /api/v1/course-chat/sessions` - 课程聊天会话
|
||||
- `GET /api/v1/sessions/{session_id}/messages` - 会话消息
|
||||
- `POST /api/v1/training/sessions` - 训练会话
|
||||
- `POST /api/v1/training/sessions/{session_id}/end` - 结束训练会话
|
||||
|
||||
#### 注意事项
|
||||
|
||||
1. **Analytics功能集成**
|
||||
- 06-Agent-Analytics主要提供数据分析和统计功能
|
||||
- 没有独立的API端点,而是增强了现有端点的数据处理能力
|
||||
- 前端已经实现了相关的统计图表和数据展示
|
||||
|
||||
2. **配置管理**
|
||||
- 确保配置属性命名的一致性(大写形式)
|
||||
- logger配置要正确引用settings对象
|
||||
|
||||
3. **类型注解完整性**
|
||||
- Pydantic v2对类型要求更严格
|
||||
- 泛型类型需要正确的导入和定义
|
||||
|
||||
这次集成非常顺利,06-Agent-Analytics的功能已完全集成到系统中,为用户提供了丰富的数据分析和统计功能。
|
||||
|
||||
### 12. 07-Agent-Admin集成经验(2025-09-21)
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **JWT认证集成问题**
|
||||
- 问题:deps.py中的get_current_user返回dict而不是User对象,导致类型不匹配
|
||||
- 解决:用户已修复deps.py,实现了真正的JWT验证和User对象返回
|
||||
- 建议:子Agent开发时要确保认证逻辑与现有系统一致
|
||||
|
||||
2. **用户角色数据不匹配**
|
||||
- 问题:数据库中存在"teacher"角色,但Pydantic schema只允许"admin|manager|trainee"
|
||||
- 解决:修复数据库中的角色数据,将"teacher"改为"manager"
|
||||
- 建议:子Agent开发时要检查数据一致性
|
||||
|
||||
3. **BaseService方法调用错误**
|
||||
- 问题:UserService调用get_multi时传递了filters参数,但BaseService不接受此参数
|
||||
- 解决:修改UserService使用正确的BaseService API,构建query对象传递
|
||||
- 建议:严格按照BaseService的接口设计进行调用
|
||||
|
||||
4. **软删除Mixin缺失**
|
||||
- 问题:UserService使用User.is_deleted字段,但User模型没有继承SoftDeleteMixin
|
||||
- 解决:让User和Team模型继承SoftDeleteMixin
|
||||
- 建议:需要软删除功能的模型都应继承SoftDeleteMixin
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **JWT认证完整实现**
|
||||
- 实现了完整的JWT token验证流程
|
||||
- 支持access_token和refresh_token
|
||||
- 正确返回User对象而不是dict
|
||||
|
||||
2. **API权限控制**
|
||||
- 管理员API正确使用require_admin依赖
|
||||
- 支持不同角色的权限验证
|
||||
- API响应格式统一
|
||||
|
||||
3. **前后端完整对接**
|
||||
- 后端API正常响应
|
||||
- 前端页面正常显示
|
||||
- 登录流程完整工作
|
||||
|
||||
4. **代码质量保证**
|
||||
- 使用black进行代码格式化
|
||||
- 修复了所有导入和类型问题
|
||||
- 保持了代码一致性
|
||||
|
||||
#### 验证清单
|
||||
|
||||
- [x] 后端服务正常启动(http://localhost:8000)
|
||||
- [x] 健康检查API正常(/health)
|
||||
- [x] API文档可访问(/docs)
|
||||
- [x] 登录API正常工作(/api/v1/auth/login)
|
||||
- [x] 用户信息API正常(/api/v1/users/me)
|
||||
- [x] 用户列表API正常(/api/v1/users/)
|
||||
- [x] 前端服务正常启动(http://localhost:3001)
|
||||
- [x] 前后端认证对接正常
|
||||
- [x] 管理员权限验证正常
|
||||
- [x] 代码格式化完成
|
||||
|
||||
#### 注意事项
|
||||
|
||||
1. **认证状态管理**
|
||||
- JWT token有过期时间,需要前端正确处理refresh
|
||||
- 不同角色用户看到不同的API响应
|
||||
|
||||
2. **数据一致性**
|
||||
- 数据库中的枚举值要与Pydantic schema保持一致
|
||||
- 软删除字段要正确配置
|
||||
|
||||
3. **服务依赖**
|
||||
- BaseService的API要正确使用
|
||||
- 不要传递不支持的参数
|
||||
|
||||
这次集成总体非常成功,07-Agent-Admin的功能已完全集成到系统中。
|
||||
|
||||
### 11. 登录问题修复经验(2025-09-22)
|
||||
|
||||
1. 现象与根因
|
||||
|
||||
- 前端登录失败,控制台报错:The requested module '/src/api/request.ts' does not provide an export named 'default'
|
||||
- 后端登录报 500:Unknown column 'users.is_deleted'(数据库缺少软删除字段)
|
||||
- 依赖冲突:httpx==0.25.2 与 cozepy==0.2.0 不兼容(cozepy 依赖 httpx<0.25.0)
|
||||
|
||||
2. 修复步骤
|
||||
|
||||
- 前端:为 `src/api/request.ts` 增加 `export default request`,修复默认导出缺失
|
||||
- 后端依赖:将 `requirements.txt` 中 httpx 降级为 `0.24.1`,同时在 `requirements-dev.txt` 移除重复锁定的 `httpx==0.25.2`
|
||||
- 数据库:为 `users` 表补齐软删除字段
|
||||
- 新增 `is_deleted TINYINT(1) NOT NULL DEFAULT 0`,`deleted_at DATETIME NULL`
|
||||
- 建议在初始化 SQL 与数据库架构文档中同步更新
|
||||
- 账户:重置默认账户(superadmin/admin/testuser)的 bcrypt 密码哈希,验证登录返回 200 并正确签发 token
|
||||
|
||||
3. 旁路与建议
|
||||
|
||||
- 本机开发可直连容器 MySQL:`mysql+aiomysql://root:root@localhost:3306/kaopeilian?charset=utf8mb4`
|
||||
- 遇到 Docker 拉取镜像超时,可暂时本地直接运行后端进行调试
|
||||
- Alembic 迁移若因环境缺少 greenlet 报错,可先执行手动 SQL 作为应急,再补齐迁移
|
||||
- 前端需确保:`VITE_USE_MOCK_DATA=false`,`VITE_API_BASE_URL=http://localhost:8000`
|
||||
|
||||
4. 回归验证清单
|
||||
|
||||
- curl 登录:`POST /api/v1/auth/login` 返回 200,结构含 `data.user` 与 `data.token`
|
||||
- `GET /api/v1/users/me` 使用 Authorization: Bearer <access_token> 返回 200
|
||||
- 前端登录后 localStorage 写入 `access_token/refresh_token` 且跳转到管理员仪表盘
|
||||
|
||||
### 9. 04-exam Agent集成经验(2025-09-21)
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **模型导入混乱**
|
||||
|
||||
- 问题:用户修改了models/__init__.py,导致模型导入不一致
|
||||
- 解决:需要同时导入所有必要的模型,包括新增的exam模型
|
||||
- 建议:子Agent开发时应该提供完整的模型导入更新
|
||||
2. **服务基类参数不匹配**
|
||||
|
||||
- 问题:`BaseService`只接受一个参数,但 `UserService`传了两个参数
|
||||
- 解决:修改UserService的初始化方法,分别设置model和db
|
||||
- 建议:统一服务类的初始化模式
|
||||
3. **数据库迁移冲突**
|
||||
|
||||
- 问题:Alembic版本冲突,迁移文件依赖不存在的版本
|
||||
- 解决:清理alembic_version表,修正迁移文件的down_revision
|
||||
- 建议:使用手动SQL脚本作为备选方案
|
||||
4. **数据类型不匹配**
|
||||
|
||||
- 问题:users表的id是BIGINT,但exam表外键定义为INT
|
||||
- 解决:修改SQL脚本,将user_id改为BIGINT类型
|
||||
- 建议:子Agent开发时要确认外键数据类型匹配
|
||||
5. **依赖注入错误**
|
||||
|
||||
- 问题:`SessionLocal`改名为 `AsyncSessionLocal`
|
||||
- 解决:更新所有相关导入
|
||||
- 建议:保持命名一致性
|
||||
6. **前后端API不匹配**
|
||||
|
||||
- 问题:前端期望的API路径与后端实现不同
|
||||
- 解决:后端实现了简化版API,前端需要适配
|
||||
- 建议:子Agent开发时参考前端API定义
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **SQL脚本包含测试数据**
|
||||
|
||||
- 在创建表的同时插入测试题目数据
|
||||
- 方便快速验证功能
|
||||
2. **独立测试脚本**
|
||||
|
||||
- 创建test_exam_api.py独立测试各个端点
|
||||
- 不依赖前端,快速验证后端功能
|
||||
3. **渐进式集成**
|
||||
|
||||
- 先确保后端服务能启动
|
||||
- 再测试API端点
|
||||
- 最后进行前后端集成
|
||||
|
||||
#### 注意事项
|
||||
|
||||
1. **服务启动问题**
|
||||
|
||||
- uvicorn启动时可能遇到各种导入错误
|
||||
- 需要逐个解决,不要急于求成
|
||||
2. **模型关系复杂**
|
||||
|
||||
- exam模块涉及多个表的关系
|
||||
- 需要仔细处理外键约束
|
||||
3. **前端已完成开发**
|
||||
|
||||
- 需要确保后端API与前端预期匹配
|
||||
- 可能需要调整API响应格式
|
||||
|
||||
### 10. 后端启动失败问题修复经验(2025-09-21)
|
||||
|
||||
#### 遇到的问题和解决方案
|
||||
|
||||
1. **Pydantic无法生成SQLAlchemy模型Schema**
|
||||
|
||||
- 问题:`PaginatedResponse[Course]` 使用了SQLAlchemy模型而不是Pydantic schema
|
||||
- 错误信息:`Unable to generate pydantic-core schema for <class 'app.models.course.Course'>`
|
||||
- 解决:
|
||||
- 将返回类型改为 `PaginatedResponse[CourseInDB]`
|
||||
- 实现分页查询逻辑,将SQLAlchemy模型转换为Pydantic模型
|
||||
- 在查询结果后使用 `CourseInDB.model_validate(course)` 进行转换
|
||||
- 建议:Service层返回值应该使用Pydantic模型而不是SQLAlchemy模型
|
||||
|
||||
2. **端口冲突问题**
|
||||
|
||||
- 问题:8000端口被多个Python进程占用
|
||||
- 解决:
|
||||
- 使用 `lsof -i :8000 | grep LISTEN` 查找占用进程
|
||||
- 使用 `kill -9 <PID>` 终止进程
|
||||
- 建议:启动前检查端口占用,或使用不同端口
|
||||
|
||||
3. **配置文件重复**
|
||||
|
||||
- 问题:存在 `app/core/database.py` 和 `app/config/database.py` 两个数据库配置文件
|
||||
- 解决:统一使用 `app/core/database.py`
|
||||
- 建议:子Agent开发时避免创建重复的配置文件
|
||||
|
||||
4. **日志文件分析困难**
|
||||
|
||||
- 问题:错误日志可能是旧的,导致误判问题
|
||||
- 解决:创建测试脚本 `test_startup.py` 逐步测试导入
|
||||
- 建议:开发诊断工具来快速定位问题
|
||||
|
||||
#### 成功经验
|
||||
|
||||
1. **创建诊断脚本**
|
||||
```python
|
||||
# test_startup.py - 逐步测试各个模块的导入
|
||||
try:
|
||||
from app.core.config import get_settings
|
||||
print("✓ 配置导入成功")
|
||||
except Exception as e:
|
||||
print(f"✗ 配置导入失败: {e}")
|
||||
```
|
||||
|
||||
2. **分页查询实现模式**
|
||||
```python
|
||||
# 将SQLAlchemy对象转换为Pydantic对象
|
||||
courses = result.scalars().all()
|
||||
course_list = [CourseInDB.model_validate(course) for course in courses]
|
||||
```
|
||||
|
||||
3. **简化启动脚本**
|
||||
- 创建 `start_backend.py` 提供更友好的启动体验
|
||||
- 显示服务地址、API文档地址等关键信息
|
||||
|
||||
#### 调试技巧
|
||||
|
||||
1. **导入错误定位**
|
||||
- 从错误堆栈的底部开始查看
|
||||
- 找到第一个项目内的文件
|
||||
- 检查该文件的导入语句
|
||||
|
||||
2. **类型错误处理**
|
||||
- Pydantic v2对类型要求更严格
|
||||
- 泛型类型参数必须是Pydantic模型
|
||||
- SQLAlchemy模型需要转换后才能使用
|
||||
|
||||
3. **服务验证步骤**
|
||||
- 先测试健康检查端点:`curl http://localhost:8000/health`
|
||||
- 再查看API文档:`http://localhost:8000/docs`
|
||||
- 最后测试具体API端点
|
||||
|
||||
#### 预防措施
|
||||
|
||||
1. **开发时注意事项**
|
||||
- Service层方法返回值使用Pydantic模型
|
||||
- 避免创建重复的配置文件
|
||||
- 提供完整的类型注解
|
||||
|
||||
2. **集成前检查清单**
|
||||
- [ ] 所有导入路径正确
|
||||
- [ ] 返回类型使用Pydantic模型
|
||||
- [ ] 配置文件路径统一
|
||||
- [ ] 端口没有被占用
|
||||
- [ ] 创建了必要的环境配置文件
|
||||
|
||||
3. **错误恢复策略**
|
||||
- 保留多个启动方式(main.py, start_backend.py, uvicorn命令)
|
||||
- 创建诊断脚本快速定位问题
|
||||
- 记录详细的错误信息和解决方案
|
||||
71
docs/规划/后端开发拆分策略/子agent/00-通用基础/project_structure.md
Normal file
71
docs/规划/后端开发拆分策略/子agent/00-通用基础/project_structure.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# 项目结构说明
|
||||
|
||||
## 项目根目录
|
||||
```
|
||||
/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/
|
||||
```
|
||||
|
||||
## 目录结构
|
||||
```
|
||||
kaopeilian-backend/
|
||||
├── app/ # 应用主目录
|
||||
│ ├── api/ # API路由
|
||||
│ │ └── v1/ # API v1版本
|
||||
│ │ ├── auth.py # 认证相关API
|
||||
│ │ ├── users.py # 用户管理API
|
||||
│ │ ├── courses.py # 课程管理API
|
||||
│ │ ├── exams.py # 考试模块API
|
||||
│ │ ├── training.py # 陪练模块API
|
||||
│ │ ├── analytics.py # 数据分析API
|
||||
│ │ └── admin.py # 系统管理API
|
||||
│ ├── config/ # 配置管理
|
||||
│ │ ├── settings.py # 系统配置
|
||||
│ │ └── database.py # 数据库配置
|
||||
│ ├── core/ # 核心功能
|
||||
│ │ ├── deps.py # 依赖注入
|
||||
│ │ ├── security.py # 安全相关
|
||||
│ │ ├── exceptions.py # 异常定义
|
||||
│ │ ├── logger.py # 日志配置
|
||||
│ │ └── middleware.py # 中间件
|
||||
│ ├── models/ # 数据库模型
|
||||
│ │ ├── base.py # 基础模型
|
||||
│ │ ├── user.py # 用户模型
|
||||
│ │ ├── course.py # 课程模型
|
||||
│ │ ├── exam.py # 考试模型
|
||||
│ │ └── training.py # 陪练模型
|
||||
│ ├── schemas/ # Pydantic模式
|
||||
│ │ ├── base.py # 基础模式
|
||||
│ │ ├── user.py # 用户模式
|
||||
│ │ ├── course.py # 课程模式
|
||||
│ │ ├── exam.py # 考试模式
|
||||
│ │ └── training.py # 陪练模式
|
||||
│ ├── services/ # 业务逻辑
|
||||
│ │ ├── base_service.py # 基础服务类
|
||||
│ │ ├── user_service.py # 用户服务
|
||||
│ │ ├── course_service.py # 课程服务
|
||||
│ │ ├── exam_service.py # 考试服务
|
||||
│ │ ├── training_service.py # 陪练服务
|
||||
│ │ └── ai/ # AI平台集成
|
||||
│ │ ├── coze/ # Coze集成
|
||||
│ │ └── dify/ # Dify集成
|
||||
│ └── main.py # 应用入口
|
||||
├── tests/ # 测试目录
|
||||
├── migrations/ # 数据库迁移
|
||||
├── requirements/ # 依赖管理
|
||||
├── docker/ # Docker配置
|
||||
└── docs/ # 项目文档
|
||||
```
|
||||
|
||||
## 关键配置文件
|
||||
- `.env` - 环境变量配置
|
||||
- `Makefile` - 开发命令集合
|
||||
- `docker-compose.yml` - Docker编排配置
|
||||
- `requirements/base.txt` - 基础依赖
|
||||
- `requirements/dev.txt` - 开发依赖
|
||||
|
||||
## 开发流程
|
||||
1. 在对应的目录创建模块文件
|
||||
2. 继承基础类进行开发
|
||||
3. 编写测试用例
|
||||
4. 运行代码检查
|
||||
5. 提交代码
|
||||
185
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/api_contract.yaml
Normal file
185
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/api_contract.yaml
Normal file
@@ -0,0 +1,185 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 认证授权模块API
|
||||
version: 1.0.0
|
||||
description: 负责用户认证、授权和Token管理
|
||||
|
||||
paths:
|
||||
/api/v1/auth/login:
|
||||
post:
|
||||
summary: 用户登录
|
||||
tags: [认证]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/x-www-form-urlencoded:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
description: 用户名或邮箱
|
||||
password:
|
||||
type: string
|
||||
description: 密码
|
||||
required:
|
||||
- username
|
||||
- password
|
||||
responses:
|
||||
200:
|
||||
description: 登录成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TokenResponse'
|
||||
400:
|
||||
description: 请求参数错误
|
||||
401:
|
||||
description: 用户名或密码错误
|
||||
403:
|
||||
description: 账号已被禁用
|
||||
|
||||
/api/v1/auth/register:
|
||||
post:
|
||||
summary: 用户注册
|
||||
tags: [认证]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UserRegister'
|
||||
responses:
|
||||
201:
|
||||
description: 注册成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TokenResponse'
|
||||
400:
|
||||
description: 参数验证失败
|
||||
409:
|
||||
description: 用户名或邮箱已存在
|
||||
|
||||
/api/v1/auth/logout:
|
||||
post:
|
||||
summary: 用户登出
|
||||
tags: [认证]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 登出成功
|
||||
401:
|
||||
description: 未授权
|
||||
|
||||
/api/v1/auth/refresh:
|
||||
post:
|
||||
summary: 刷新Token
|
||||
tags: [认证]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
refresh_token:
|
||||
type: string
|
||||
required:
|
||||
- refresh_token
|
||||
responses:
|
||||
200:
|
||||
description: 刷新成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TokenResponse'
|
||||
401:
|
||||
description: 刷新Token无效
|
||||
|
||||
/api/v1/auth/reset-password:
|
||||
post:
|
||||
summary: 重置密码请求
|
||||
tags: [认证]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
required:
|
||||
- email
|
||||
responses:
|
||||
200:
|
||||
description: 重置邮件已发送
|
||||
404:
|
||||
description: 邮箱不存在
|
||||
|
||||
components:
|
||||
schemas:
|
||||
UserRegister:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
minLength: 3
|
||||
maxLength: 20
|
||||
pattern: '^[a-zA-Z0-9_-]+$'
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
password:
|
||||
type: string
|
||||
minLength: 8
|
||||
confirm_password:
|
||||
type: string
|
||||
required:
|
||||
- username
|
||||
- email
|
||||
- password
|
||||
- confirm_password
|
||||
|
||||
TokenResponse:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: integer
|
||||
example: 200
|
||||
message:
|
||||
type: string
|
||||
example: success
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
access_token:
|
||||
type: string
|
||||
refresh_token:
|
||||
type: string
|
||||
token_type:
|
||||
type: string
|
||||
example: bearer
|
||||
expires_in:
|
||||
type: integer
|
||||
example: 1800
|
||||
user:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
username:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
119
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/checklist.md
Normal file
119
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/checklist.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Agent-Auth 开发检查清单
|
||||
|
||||
## 开发前准备
|
||||
- [ ] 阅读并理解 `prompt.md` 中的所有要求
|
||||
- [ ] 熟悉 `context.md` 中的项目结构和依赖
|
||||
- [ ] 查看 `api_contract.yaml` 了解API规范
|
||||
- [ ] 设置开发环境,安装所有依赖
|
||||
- [ ] 创建 feature/auth 分支
|
||||
|
||||
## 核心功能开发
|
||||
|
||||
### 1. 数据库模型
|
||||
- [ ] 创建 `app/models/user.py` 用户模型
|
||||
- [ ] 继承 BaseModel 和 AuditMixin
|
||||
- [ ] 添加必要的索引
|
||||
- [ ] 创建数据库迁移脚本
|
||||
|
||||
### 2. Schema定义
|
||||
- [ ] 创建 `app/schemas/auth.py`
|
||||
- [ ] 定义 UserLogin schema
|
||||
- [ ] 定义 UserRegister schema
|
||||
- [ ] 定义 Token schema
|
||||
- [ ] 添加输入验证规则
|
||||
|
||||
### 3. 安全功能
|
||||
- [ ] 完善 `app/core/security.py`
|
||||
- [ ] 实现密码加密函数
|
||||
- [ ] 实现密码验证函数
|
||||
- [ ] 实现JWT Token生成
|
||||
- [ ] 实现JWT Token验证
|
||||
|
||||
### 4. 依赖注入
|
||||
- [ ] 创建/完善 `app/api/deps.py`
|
||||
- [ ] 实现 get_current_user
|
||||
- [ ] 实现 get_current_active_user
|
||||
- [ ] 实现角色检查器(require_admin等)
|
||||
|
||||
### 5. 业务服务
|
||||
- [ ] 创建 `app/services/auth_service.py`
|
||||
- [ ] 实现用户认证逻辑
|
||||
- [ ] 实现用户创建逻辑
|
||||
- [ ] 实现Token管理逻辑
|
||||
- [ ] 添加错误处理
|
||||
|
||||
### 6. API路由
|
||||
- [ ] 创建 `app/api/v1/auth.py`
|
||||
- [ ] 实现登录端点
|
||||
- [ ] 实现注册端点
|
||||
- [ ] 实现登出端点
|
||||
- [ ] 实现Token刷新端点
|
||||
- [ ] 实现密码重置端点
|
||||
|
||||
### 7. 中间件和异常
|
||||
- [ ] 实现认证中间件
|
||||
- [ ] 添加请求限流
|
||||
- [ ] 处理认证异常
|
||||
|
||||
## 测试开发
|
||||
|
||||
### 单元测试
|
||||
- [ ] 创建 `tests/unit/test_auth_service.py`
|
||||
- [ ] 测试密码加密和验证
|
||||
- [ ] 测试Token生成和验证
|
||||
- [ ] 测试用户认证逻辑
|
||||
- [ ] 测试用户创建逻辑
|
||||
|
||||
### 集成测试
|
||||
- [ ] 创建 `tests/integration/test_auth_api.py`
|
||||
- [ ] 测试登录流程
|
||||
- [ ] 测试注册流程
|
||||
- [ ] 测试Token刷新
|
||||
- [ ] 测试权限验证
|
||||
|
||||
### 性能测试
|
||||
- [ ] 测试登录响应时间
|
||||
- [ ] 测试Token验证性能
|
||||
- [ ] 测试并发登录
|
||||
|
||||
## 安全检查
|
||||
- [ ] 密码使用bcrypt加密
|
||||
- [ ] Token设置合理过期时间
|
||||
- [ ] 实现登录失败限制
|
||||
- [ ] 防止暴力破解
|
||||
- [ ] SQL注入防护
|
||||
- [ ] XSS防护
|
||||
|
||||
## 文档更新
|
||||
- [ ] 更新API文档
|
||||
- [ ] 添加使用示例
|
||||
- [ ] 更新README
|
||||
- [ ] 编写部署说明
|
||||
|
||||
## 代码质量
|
||||
- [ ] 运行 `make format` 格式化代码
|
||||
- [ ] 运行 `make lint` 检查代码风格
|
||||
- [ ] 运行 `make type-check` 类型检查
|
||||
- [ ] 运行 `make test` 所有测试通过
|
||||
- [ ] 代码覆盖率 > 80%
|
||||
|
||||
## 集成验证
|
||||
- [ ] 与其他模块集成测试
|
||||
- [ ] 验证依赖注入正常工作
|
||||
- [ ] 验证中间件正常拦截
|
||||
- [ ] 验证日志记录完整
|
||||
|
||||
## 提交前确认
|
||||
- [ ] 所有功能已实现
|
||||
- [ ] 所有测试通过
|
||||
- [ ] 文档已更新
|
||||
- [ ] 代码已审查
|
||||
- [ ] 没有硬编码的密钥
|
||||
- [ ] 没有调试代码
|
||||
- [ ] commit信息符合规范
|
||||
|
||||
## 部署准备
|
||||
- [ ] 环境变量已配置
|
||||
- [ ] 生产配置已准备
|
||||
- [ ] 性能优化已完成
|
||||
- [ ] 监控指标已添加
|
||||
137
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/context.md
Normal file
137
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/context.md
Normal file
@@ -0,0 +1,137 @@
|
||||
# Agent-Auth 上下文信息
|
||||
|
||||
## 重要规划文档
|
||||
在开始开发前,请确保你已经理解以下关键文档:
|
||||
- `../../协作机制设计.md` - 特别是全局上下文(GlobalContext)和服务间调用机制
|
||||
- `../../模块分工指南.md` - 了解Auth模块的职责边界(第2.1节)
|
||||
- `../../开发规范文档.md` - 编码标准和API设计规范
|
||||
- `../../统一基础代码.md` - 可复用的代码模板
|
||||
|
||||
## 项目位置
|
||||
|
||||
- 项目根目录: `/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 你的工作目录: `app/api/v1/auth.py`, `app/core/security.py`, `app/services/auth_service.py`
|
||||
|
||||
## 重要依赖文件
|
||||
|
||||
### 1. 基础模型 (`app/models/base.py`)
|
||||
|
||||
已提供BaseModel, SoftDeleteMixin, AuditMixin等基类
|
||||
|
||||
### 2. 用户模型 (`app/models/user.py`) - 需要你创建
|
||||
|
||||
```python
|
||||
from sqlalchemy import Column, String, Boolean, Enum
|
||||
from app.models.base import BaseModel, AuditMixin
|
||||
|
||||
class User(BaseModel, AuditMixin):
|
||||
__tablename__ = "users"
|
||||
|
||||
username = Column(String(50), unique=True, nullable=False, index=True)
|
||||
email = Column(String(100), unique=True, nullable=False, index=True)
|
||||
password_hash = Column(String(200), nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superuser = Column(Boolean, default=False)
|
||||
role = Column(String(20), default="trainee") # trainee, manager, admin
|
||||
```
|
||||
|
||||
### 3. 基础Schema (`app/schemas/base.py`)
|
||||
|
||||
已提供BaseSchema, ResponseModel, ErrorResponse等基类
|
||||
|
||||
### 4. 异常处理 (`app/core/exceptions.py`)
|
||||
|
||||
已定义所有标准异常类
|
||||
|
||||
### 5. 日志系统 (`app/core/logger.py`)
|
||||
|
||||
已配置结构化日志
|
||||
|
||||
### 6. 配置管理 (`app/config/settings.py`)
|
||||
|
||||
关键配置项:
|
||||
|
||||
- SECRET_KEY - JWT密钥
|
||||
- ALGORITHM - JWT算法(默认HS256)
|
||||
- ACCESS_TOKEN_EXPIRE_MINUTES - 访问Token过期时间(默认30分钟)
|
||||
- REFRESH_TOKEN_EXPIRE_DAYS - 刷新Token过期时间(默认7天)
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
```sql
|
||||
CREATE TABLE users (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
email VARCHAR(100) UNIQUE NOT NULL,
|
||||
password_hash VARCHAR(200) NOT NULL,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
is_superuser BOOLEAN DEFAULT FALSE,
|
||||
role VARCHAR(20) DEFAULT 'trainee',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
created_by BIGINT,
|
||||
updated_by BIGINT,
|
||||
INDEX idx_username (username),
|
||||
INDEX idx_email (email)
|
||||
);
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
```bash
|
||||
# .env 文件中的认证相关配置
|
||||
SECRET_KEY="your-secret-key-here-must-be-at-least-32-chars"
|
||||
ALGORITHM="HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
```
|
||||
|
||||
## 测试账号
|
||||
|
||||
用于开发测试的默认账号:
|
||||
|
||||
- 超级管理员: superadmin / Superadmin123!
|
||||
- 系统管理员: admin / Admin123!
|
||||
- 测试学员: testuser / TestPass123!
|
||||
|
||||
## 错误码约定
|
||||
|
||||
- 1001: 用户名或密码错误
|
||||
- 1002: 账号已被禁用
|
||||
- 1003: Token无效或已过期
|
||||
- 1004: 权限不足
|
||||
- 1005: 用户名已存在
|
||||
- 1006: 邮箱已存在
|
||||
|
||||
## 关键流程
|
||||
|
||||
### 登录流程
|
||||
|
||||
1. 接收用户名和密码
|
||||
2. 验证用户身份
|
||||
3. 检查账号状态
|
||||
4. 生成访问Token和刷新Token
|
||||
5. 返回Token信息
|
||||
|
||||
### 注册流程
|
||||
|
||||
1. 验证输入数据
|
||||
2. 检查用户名和邮箱唯一性
|
||||
3. 加密密码
|
||||
4. 创建用户记录
|
||||
5. 自动登录并返回Token
|
||||
|
||||
### Token刷新流程
|
||||
|
||||
1. 验证刷新Token
|
||||
2. 检查Token是否在黑名单
|
||||
3. 生成新的访问Token
|
||||
4. 可选:轮换刷新Token
|
||||
|
||||
## 安全最佳实践
|
||||
|
||||
1. 使用bcrypt加密密码,cost factor设为12
|
||||
2. JWT Token使用RS256算法(生产环境)
|
||||
3. 实现Token黑名单机制(使用Redis)
|
||||
4. 登录失败5次锁定账号15分钟
|
||||
5. 敏感操作记录审计日志
|
||||
93
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/dependencies.md
Normal file
93
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/dependencies.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# Agent-Auth 依赖关系
|
||||
|
||||
## 依赖概览
|
||||
Agent-Auth是基础模块,**不依赖其他业务模块**,但依赖系统基础设施。
|
||||
|
||||
## 输入依赖
|
||||
|
||||
### 1. 系统基础设施
|
||||
- `app/config/settings.py` - 系统配置
|
||||
- `app/config/database.py` - 数据库连接
|
||||
- `app/core/logger.py` - 日志系统
|
||||
- `app/models/base.py` - 基础模型类
|
||||
- `app/schemas/base.py` - 基础Schema类
|
||||
|
||||
### 2. 第三方库
|
||||
- `fastapi` - Web框架
|
||||
- `sqlalchemy` - ORM
|
||||
- `passlib[bcrypt]` - 密码加密
|
||||
- `python-jose[cryptography]` - JWT处理
|
||||
- `redis` - 缓存(用于Token黑名单)
|
||||
|
||||
### 3. 环境变量
|
||||
```bash
|
||||
SECRET_KEY=必需
|
||||
ALGORITHM=可选(默认HS256)
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=可选(默认30)
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=可选(默认7)
|
||||
```
|
||||
|
||||
## 输出接口
|
||||
|
||||
### 1. 依赖注入函数
|
||||
其他所有模块都会使用这些函数:
|
||||
```python
|
||||
# app/api/deps.py 或 app/core/deps.py
|
||||
async def get_current_user() -> User
|
||||
async def get_current_active_user() -> User
|
||||
async def get_optional_current_user() -> Optional[User]
|
||||
|
||||
# 角色检查器
|
||||
require_admin = RoleChecker(["admin"])
|
||||
require_manager = RoleChecker(["admin", "manager"])
|
||||
require_trainer = RoleChecker(["admin", "manager", "trainer"])
|
||||
```
|
||||
|
||||
### 2. 安全工具函数
|
||||
```python
|
||||
# app/core/security.py
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool
|
||||
def get_password_hash(password: str) -> str
|
||||
def create_access_token(subject: int, **kwargs) -> str
|
||||
def create_refresh_token(subject: int) -> str
|
||||
def verify_token(token: str) -> dict
|
||||
```
|
||||
|
||||
### 3. 数据模型
|
||||
```python
|
||||
# app/models/user.py
|
||||
class User(BaseModel, AuditMixin):
|
||||
# 被所有其他模块引用的用户模型
|
||||
pass
|
||||
```
|
||||
|
||||
### 4. API端点
|
||||
```
|
||||
POST /api/v1/auth/login
|
||||
POST /api/v1/auth/register
|
||||
POST /api/v1/auth/logout
|
||||
POST /api/v1/auth/refresh
|
||||
POST /api/v1/auth/reset-password
|
||||
```
|
||||
|
||||
## 被依赖情况
|
||||
|
||||
以下模块依赖Auth模块:
|
||||
- **所有模块** - 使用认证和权限检查
|
||||
- Agent-User - 使用User模型
|
||||
- Agent-Course - 使用get_current_user
|
||||
- Agent-Exam - 使用get_current_user
|
||||
- Agent-Training - 使用get_current_user
|
||||
- Agent-Analytics - 使用权限检查
|
||||
- Agent-Admin - 使用require_admin
|
||||
|
||||
## 接口稳定性
|
||||
⚠️ **关键接口,需保持稳定**
|
||||
- 修改认证逻辑会影响所有模块
|
||||
- Token格式变更需要通知所有模块
|
||||
- User模型字段变更需要评估影响
|
||||
|
||||
## 测试依赖
|
||||
- 需要模拟Redis服务
|
||||
- 需要测试数据库
|
||||
- 需要模拟邮件服务(密码重置)
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
认证API路由示例代码
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_db
|
||||
from app.core.exceptions import UnauthorizedError, ConflictError
|
||||
from app.schemas.auth import UserRegister, Token, PasswordReset
|
||||
from app.schemas.base import ResponseModel
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["认证"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=ResponseModel[Token], summary="用户登录")
|
||||
async def login(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
用户登录接口
|
||||
|
||||
- **username**: 用户名或邮箱
|
||||
- **password**: 密码
|
||||
|
||||
返回访问令牌和刷新令牌
|
||||
"""
|
||||
auth_service = AuthService(db)
|
||||
|
||||
# 验证用户
|
||||
user = await auth_service.authenticate_user(
|
||||
username=form_data.username,
|
||||
password=form_data.password
|
||||
)
|
||||
|
||||
if not user:
|
||||
raise UnauthorizedError("用户名或密码错误")
|
||||
|
||||
# 创建Token
|
||||
token = await auth_service.create_tokens(user)
|
||||
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="登录成功",
|
||||
data=token
|
||||
)
|
||||
|
||||
|
||||
@router.post("/register", response_model=ResponseModel[Token], status_code=status.HTTP_201_CREATED)
|
||||
async def register(
|
||||
user_data: UserRegister,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
用户注册接口
|
||||
|
||||
注册成功后自动登录,返回Token
|
||||
"""
|
||||
# 验证密码一致性
|
||||
if user_data.password != user_data.confirm_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="两次输入的密码不一致"
|
||||
)
|
||||
|
||||
auth_service = AuthService(db)
|
||||
|
||||
try:
|
||||
# 创建用户
|
||||
user = await auth_service.create_user(user_data)
|
||||
|
||||
# 自动登录
|
||||
token = await auth_service.create_tokens(user)
|
||||
|
||||
return ResponseModel(
|
||||
code=201,
|
||||
message="注册成功",
|
||||
data=token
|
||||
)
|
||||
except ConflictError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=str(e)
|
||||
)
|
||||
|
||||
|
||||
@router.post("/logout", response_model=ResponseModel)
|
||||
async def logout(
|
||||
token: str = Depends(get_current_token),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
用户登出接口
|
||||
|
||||
将当前Token加入黑名单
|
||||
"""
|
||||
auth_service = AuthService(db)
|
||||
await auth_service.logout(token)
|
||||
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="登出成功"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=ResponseModel[Token])
|
||||
async def refresh_token(
|
||||
refresh_token: str,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
刷新访问令牌
|
||||
|
||||
使用刷新令牌获取新的访问令牌
|
||||
"""
|
||||
auth_service = AuthService(db)
|
||||
|
||||
try:
|
||||
token = await auth_service.refresh_access_token(refresh_token)
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="刷新成功",
|
||||
data=token
|
||||
)
|
||||
except UnauthorizedError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="刷新令牌无效或已过期"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reset-password/request", response_model=ResponseModel)
|
||||
async def request_password_reset(
|
||||
email: str,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
请求重置密码
|
||||
|
||||
向用户邮箱发送重置链接
|
||||
"""
|
||||
auth_service = AuthService(db)
|
||||
|
||||
# 查找用户
|
||||
user = await auth_service.get_user_by_email(email)
|
||||
if not user:
|
||||
# 为了安全,即使用户不存在也返回成功
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="如果邮箱存在,重置链接已发送"
|
||||
)
|
||||
|
||||
# 生成重置令牌
|
||||
reset_token = await auth_service.create_password_reset_token(user)
|
||||
|
||||
# TODO: 发送邮件
|
||||
# await send_reset_email(email, reset_token)
|
||||
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="如果邮箱存在,重置链接已发送"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reset-password/confirm", response_model=ResponseModel)
|
||||
async def reset_password(
|
||||
reset_data: PasswordReset,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
确认重置密码
|
||||
|
||||
使用重置令牌设置新密码
|
||||
"""
|
||||
auth_service = AuthService(db)
|
||||
|
||||
try:
|
||||
await auth_service.reset_password(
|
||||
token=reset_data.token,
|
||||
new_password=reset_data.new_password
|
||||
)
|
||||
|
||||
return ResponseModel(
|
||||
code=200,
|
||||
message="密码重置成功"
|
||||
)
|
||||
except UnauthorizedError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="重置令牌无效或已过期"
|
||||
)
|
||||
|
||||
|
||||
# 辅助函数
|
||||
async def get_current_token(
|
||||
authorization: str = Depends(oauth2_scheme)
|
||||
) -> str:
|
||||
"""获取当前请求的Token"""
|
||||
return authorization
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
认证服务示例代码
|
||||
"""
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.core.security import verify_password, get_password_hash, create_access_token, create_refresh_token
|
||||
from app.core.exceptions import UnauthorizedError, ConflictError, ForbiddenError
|
||||
from app.core.logger import logger
|
||||
from app.models.user import User
|
||||
from app.schemas.auth import UserRegister, Token
|
||||
|
||||
|
||||
class AuthService:
|
||||
"""认证服务类"""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def authenticate_user(self, username: str, password: str) -> Optional[User]:
|
||||
"""
|
||||
验证用户身份
|
||||
|
||||
Args:
|
||||
username: 用户名或邮箱
|
||||
password: 密码
|
||||
|
||||
Returns:
|
||||
验证成功返回User对象,失败返回None
|
||||
"""
|
||||
# 查询用户(支持用户名或邮箱登录)
|
||||
query = select(User).where(
|
||||
(User.username == username) | (User.email == username)
|
||||
)
|
||||
result = await self.db.execute(query)
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
logger.warning("登录失败:用户不存在", username=username)
|
||||
return None
|
||||
|
||||
# 验证密码
|
||||
if not verify_password(password, user.password_hash):
|
||||
logger.warning("登录失败:密码错误", user_id=user.id, username=username)
|
||||
# TODO: 记录失败次数,实现账号锁定
|
||||
return None
|
||||
|
||||
# 检查账号状态
|
||||
if not user.is_active:
|
||||
logger.warning("登录失败:账号已禁用", user_id=user.id, username=username)
|
||||
raise ForbiddenError("账号已被禁用")
|
||||
|
||||
logger.info("用户登录成功", user_id=user.id, username=user.username)
|
||||
return user
|
||||
|
||||
async def create_user(self, user_data: UserRegister) -> User:
|
||||
"""
|
||||
创建新用户
|
||||
|
||||
Args:
|
||||
user_data: 用户注册数据
|
||||
|
||||
Returns:
|
||||
创建的用户对象
|
||||
|
||||
Raises:
|
||||
ConflictError: 用户名或邮箱已存在
|
||||
"""
|
||||
# 检查用户名是否存在
|
||||
query = select(User).where(User.username == user_data.username)
|
||||
result = await self.db.execute(query)
|
||||
if result.scalar_one_or_none():
|
||||
raise ConflictError("用户名已存在")
|
||||
|
||||
# 检查邮箱是否存在
|
||||
query = select(User).where(User.email == user_data.email)
|
||||
result = await self.db.execute(query)
|
||||
if result.scalar_one_or_none():
|
||||
raise ConflictError("邮箱已存在")
|
||||
|
||||
# 创建用户
|
||||
user = User(
|
||||
username=user_data.username,
|
||||
email=user_data.email,
|
||||
password_hash=get_password_hash(user_data.password),
|
||||
is_active=True,
|
||||
is_superuser=False,
|
||||
role="trainee" # 默认角色为学员
|
||||
)
|
||||
|
||||
self.db.add(user)
|
||||
await self.db.commit()
|
||||
await self.db.refresh(user)
|
||||
|
||||
logger.info("用户注册成功", user_id=user.id, username=user.username)
|
||||
return user
|
||||
|
||||
async def create_tokens(self, user: User) -> Token:
|
||||
"""
|
||||
为用户创建访问令牌和刷新令牌
|
||||
|
||||
Args:
|
||||
user: 用户对象
|
||||
|
||||
Returns:
|
||||
Token对象
|
||||
"""
|
||||
# 创建访问令牌
|
||||
access_token = create_access_token(
|
||||
subject=user.id,
|
||||
role=user.role,
|
||||
username=user.username
|
||||
)
|
||||
|
||||
# 创建刷新令牌
|
||||
refresh_token = create_refresh_token(subject=user.id)
|
||||
|
||||
return Token(
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
token_type="bearer",
|
||||
expires_in=1800, # 30分钟
|
||||
user={
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"role": user.role
|
||||
}
|
||||
)
|
||||
|
||||
async def logout(self, token: str) -> None:
|
||||
"""
|
||||
用户登出,将token加入黑名单
|
||||
|
||||
Args:
|
||||
token: 要失效的token
|
||||
"""
|
||||
# TODO: 将token加入Redis黑名单
|
||||
# redis_key = f"blacklist:{token}"
|
||||
# await redis.setex(redis_key, 3600, "1") # 设置1小时过期
|
||||
|
||||
logger.info("用户登出成功")
|
||||
|
||||
async def refresh_access_token(self, refresh_token: str) -> Token:
|
||||
"""
|
||||
使用刷新令牌获取新的访问令牌
|
||||
|
||||
Args:
|
||||
refresh_token: 刷新令牌
|
||||
|
||||
Returns:
|
||||
新的Token对象
|
||||
"""
|
||||
# TODO: 验证刷新令牌
|
||||
# TODO: 检查是否在黑名单
|
||||
# TODO: 生成新的访问令牌
|
||||
# TODO: 可选 - 轮换刷新令牌
|
||||
|
||||
pass
|
||||
188
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/prompt.md
Normal file
188
docs/规划/后端开发拆分策略/子agent/01-Agent-Auth/prompt.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# Agent-Auth 提示词
|
||||
|
||||
## 基础规范引用
|
||||
**重要**: 开始开发前,你必须先阅读并严格遵循以下文件:
|
||||
- `00-通用基础/base_prompt.md` - 通用开发规范(代码格式、错误处理、日志规范等)
|
||||
- `00-通用基础/project_structure.md` - 项目目录结构说明
|
||||
|
||||
## 你的角色
|
||||
你是Agent-Auth,负责考培练系统的**认证授权模块**开发。你的代码将成为整个系统的安全基石,其他所有模块都将依赖你的认证服务。
|
||||
|
||||
## 核心职责
|
||||
1. 实现用户登录、注册、登出功能
|
||||
2. 管理JWT Token的生成和验证
|
||||
3. 提供权限检查中间件和依赖注入
|
||||
4. 实现密码重置和账号激活功能
|
||||
5. 确保系统的安全性
|
||||
|
||||
## 你需要开发的文件
|
||||
|
||||
### 1. API路由 (`app/api/v1/auth.py`)
|
||||
```python
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_db
|
||||
from app.services.auth_service import AuthService
|
||||
from app.schemas.auth import Token, UserLogin, UserRegister
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/login", response_model=ResponseModel[Token])
|
||||
async def login(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""用户登录"""
|
||||
# 实现登录逻辑
|
||||
pass
|
||||
|
||||
@router.post("/register", response_model=ResponseModel[Token])
|
||||
async def register(
|
||||
user_data: UserRegister,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""用户注册"""
|
||||
# 实现注册逻辑
|
||||
pass
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout():
|
||||
"""用户登出"""
|
||||
# 实现登出逻辑
|
||||
pass
|
||||
|
||||
@router.post("/refresh", response_model=ResponseModel[Token])
|
||||
async def refresh_token(refresh_token: str):
|
||||
"""刷新Token"""
|
||||
# 实现Token刷新逻辑
|
||||
pass
|
||||
|
||||
@router.post("/reset-password")
|
||||
async def reset_password(email: str):
|
||||
"""重置密码"""
|
||||
# 实现密码重置逻辑
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. 安全核心功能 (`app/core/security.py`)
|
||||
已在基础代码中部分实现,你需要完善:
|
||||
- 密码加密和验证
|
||||
- JWT Token生成和验证
|
||||
- 权限验证装饰器
|
||||
|
||||
### 3. 认证依赖注入 (`app/core/deps.py` 或 `app/api/deps.py`)
|
||||
```python
|
||||
async def get_current_user(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
token: str = Depends(oauth2_scheme)
|
||||
) -> User:
|
||||
"""获取当前登录用户"""
|
||||
# 实现逻辑
|
||||
pass
|
||||
|
||||
async def require_admin(user: User = Depends(get_current_user)) -> User:
|
||||
"""需要管理员权限"""
|
||||
# 实现逻辑
|
||||
pass
|
||||
```
|
||||
|
||||
### 4. Schema定义 (`app/schemas/auth.py`)
|
||||
```python
|
||||
from pydantic import EmailStr, Field
|
||||
from app.schemas.base import BaseSchema
|
||||
|
||||
class UserLogin(BaseSchema):
|
||||
username: str = Field(..., description="用户名或邮箱")
|
||||
password: str = Field(..., description="密码")
|
||||
|
||||
class UserRegister(BaseSchema):
|
||||
username: str = Field(..., min_length=3, max_length=20)
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=8)
|
||||
confirm_password: str
|
||||
|
||||
class Token(BaseSchema):
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
```
|
||||
|
||||
### 5. 认证服务 (`app/services/auth_service.py`)
|
||||
```python
|
||||
from app.services.base_service import BaseService
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def authenticate_user(self, username: str, password: str):
|
||||
"""验证用户身份"""
|
||||
pass
|
||||
|
||||
async def create_user(self, user_data: UserRegister):
|
||||
"""创建新用户"""
|
||||
pass
|
||||
|
||||
async def create_tokens(self, user_id: int):
|
||||
"""创建访问令牌和刷新令牌"""
|
||||
pass
|
||||
```
|
||||
|
||||
### 6. 测试用例 (`tests/unit/test_auth.py`)
|
||||
```python
|
||||
import pytest
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_registration(db_session):
|
||||
"""测试用户注册"""
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_login(db_session):
|
||||
"""测试用户登录"""
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_token_refresh(db_session):
|
||||
"""测试Token刷新"""
|
||||
pass
|
||||
```
|
||||
|
||||
## 与其他模块的接口
|
||||
|
||||
### 提供给其他模块的功能
|
||||
1. `get_current_user` - 获取当前登录用户
|
||||
2. `require_admin` - 需要管理员权限
|
||||
3. `require_manager` - 需要管理者权限
|
||||
4. `create_access_token` - 创建访问令牌
|
||||
5. `verify_password` - 验证密码
|
||||
6. `get_password_hash` - 获取密码哈希
|
||||
|
||||
### API端点
|
||||
- POST `/api/v1/auth/login` - 用户登录
|
||||
- POST `/api/v1/auth/register` - 用户注册
|
||||
- POST `/api/v1/auth/logout` - 用户登出
|
||||
- POST `/api/v1/auth/refresh` - 刷新Token
|
||||
- POST `/api/v1/auth/reset-password` - 重置密码
|
||||
|
||||
## 安全要求
|
||||
1. 密码必须使用bcrypt加密存储
|
||||
2. JWT Token必须设置合理的过期时间
|
||||
3. 刷新Token必须与访问Token分开存储
|
||||
4. 实现登录失败次数限制
|
||||
5. 敏感操作需要二次验证
|
||||
|
||||
## 性能要求
|
||||
1. 登录响应时间 < 200ms
|
||||
2. Token验证时间 < 50ms
|
||||
3. 合理使用Redis缓存Token黑名单
|
||||
|
||||
## 参考资源
|
||||
- FastAPI Security文档: https://fastapi.tiangolo.com/tutorial/security/
|
||||
- JWT最佳实践: https://tools.ietf.org/html/rfc8725
|
||||
- OWASP认证指南: https://owasp.org/www-project-cheat-sheets/
|
||||
122
docs/规划/后端开发拆分策略/子agent/02-Agent-User/api_contract.yaml
Normal file
122
docs/规划/后端开发拆分策略/子agent/02-Agent-User/api_contract.yaml
Normal file
@@ -0,0 +1,122 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 用户管理模块API
|
||||
version: 1.0.0
|
||||
description: 用户与团队管理的最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/users/me:
|
||||
get:
|
||||
summary: 获取当前用户信息
|
||||
tags: [用户]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ResponseUser'
|
||||
401:
|
||||
description: 未授权
|
||||
|
||||
/api/v1/users:
|
||||
get:
|
||||
summary: 用户列表
|
||||
tags: [用户]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: query
|
||||
name: page
|
||||
schema: { type: integer, minimum: 1, default: 1 }
|
||||
- in: query
|
||||
name: size
|
||||
schema: { type: integer, minimum: 1, maximum: 100, default: 10 }
|
||||
- in: query
|
||||
name: role
|
||||
schema: { type: string }
|
||||
- in: query
|
||||
name: is_active
|
||||
schema: { type: boolean }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
403:
|
||||
description: 权限不足
|
||||
|
||||
post:
|
||||
summary: 创建用户(管理员)
|
||||
tags: [用户]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UserCreate'
|
||||
responses:
|
||||
201:
|
||||
description: 已创建
|
||||
409:
|
||||
description: 用户名或邮箱冲突
|
||||
|
||||
/api/v1/users/{id}:
|
||||
get:
|
||||
summary: 获取指定用户
|
||||
tags: [用户]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
404:
|
||||
description: 未找到
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
|
||||
schemas:
|
||||
ResponseUser:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: integer
|
||||
example: 200
|
||||
message:
|
||||
type: string
|
||||
example: success
|
||||
data:
|
||||
$ref: '#/components/schemas/User'
|
||||
|
||||
User:
|
||||
type: object
|
||||
properties:
|
||||
id: { type: integer }
|
||||
username: { type: string }
|
||||
email: { type: string }
|
||||
role: { type: string }
|
||||
is_active: { type: boolean }
|
||||
|
||||
UserCreate:
|
||||
type: object
|
||||
required: [username, email, password]
|
||||
properties:
|
||||
username: { type: string, minLength: 3, maxLength: 20 }
|
||||
email: { type: string, format: email }
|
||||
password: { type: string, minLength: 8 }
|
||||
role:
|
||||
type: string
|
||||
enum: [trainee, manager, admin]
|
||||
|
||||
21
docs/规划/后端开发拆分策略/子agent/02-Agent-User/checklist.md
Normal file
21
docs/规划/后端开发拆分策略/子agent/02-Agent-User/checklist.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Agent-User 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读 `00-通用基础/base_prompt.md`、`essential_docs.md`
|
||||
- [ ] 通读 `模块分工指南.md` 与 `协作机制设计.md`
|
||||
|
||||
## 最小功能
|
||||
- [ ] `GET /api/v1/users/me` 返回当前用户
|
||||
- [ ] `GET /api/v1/users` 支持分页与筛选(role、is_active)
|
||||
- [ ] `POST /api/v1/users` 管理员创建用户(校验唯一性、加密密码)
|
||||
- [ ] `GET /api/v1/users/{id}` 获取用户详情
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 认证与权限检查(`get_current_user`、`require_admin`)
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过格式化/静态检查(Black/isort/flake8/mypy)
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
29
docs/规划/后端开发拆分策略/子agent/02-Agent-User/context.md
Normal file
29
docs/规划/后端开发拆分策略/子agent/02-Agent-User/context.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Agent-User 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth 认证与角色检查(`get_current_user`、`require_admin`)、数据库与Redis
|
||||
- 输出接口:用户与团队查询/维护 API 与服务方法,供 Course/Exam/Training/Analytics 使用
|
||||
|
||||
## 关键约束
|
||||
- 安全:认证必需;普通用户仅能操作自身;管理员可管理全量
|
||||
- 性能:用户列表分页查询 ≤ 200ms(本地);常用筛选字段建索引
|
||||
- 观测:登录、变更、角色调整等关键动作记录结构化日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:复用通用 `.env`,无新增必需项
|
||||
- 测试账号:与 Auth 模块一致(superadmin/admin/testuser)
|
||||
- 关联模型/表:`users`、`teams`、`user_teams`
|
||||
|
||||
## 开发完成状态
|
||||
- ✅ 用户管理模块已完成
|
||||
- ✅ 数据模型:User、Team、UserTeam
|
||||
- ✅ 服务层:UserService(CRUD、认证、团队管理)
|
||||
- ✅ Auth模块:登录、令牌刷新、登出
|
||||
- ✅ API路由:用户和认证相关端点
|
||||
- ✅ 数据库表结构已创建
|
||||
- ⚠️ SQLAlchemy 2.0兼容性问题需要注意
|
||||
|
||||
17
docs/规划/后端开发拆分策略/子agent/02-Agent-User/examples/README.md
Normal file
17
docs/规划/后端开发拆分策略/子agent/02-Agent-User/examples/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Agent-User 示例(最小)
|
||||
|
||||
- users.me:返回当前登录用户信息。
|
||||
|
||||
```python
|
||||
# app/api/v1/users.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_current_user
|
||||
from app.schemas.base import ResponseModel
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/me", response_model=ResponseModel)
|
||||
async def get_current_user_info(current_user: User = Depends(get_current_user)):
|
||||
return ResponseModel(code=200, message="success", data=current_user)
|
||||
```
|
||||
22
docs/规划/后端开发拆分策略/子agent/02-Agent-User/prompt.md
Normal file
22
docs/规划/后端开发拆分策略/子agent/02-Agent-User/prompt.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Agent-User 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:用户与团队管理(用户 CRUD、个人资料、角色与团队管理、列表筛选)
|
||||
- 依赖模块:Auth(认证与权限)
|
||||
- 对外输出:用户查询服务、团队查询服务、管理端用户维护 API
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/users.py`、`app/services/user_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(`get_current_user`、`require_admin`)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
138
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/api_contract.yaml
Normal file
138
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/api_contract.yaml
Normal file
@@ -0,0 +1,138 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 课程管理模块API
|
||||
version: 1.0.0
|
||||
description: 课程与知识点的最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/courses:
|
||||
get:
|
||||
summary: 课程列表
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: query
|
||||
name: page
|
||||
schema: { type: integer, minimum: 1, default: 1 }
|
||||
- in: query
|
||||
name: size
|
||||
schema: { type: integer, minimum: 1, maximum: 100, default: 10 }
|
||||
- in: query
|
||||
name: status
|
||||
schema: { type: string }
|
||||
- in: query
|
||||
name: category
|
||||
schema: { type: string }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
post:
|
||||
summary: 创建课程(管理员)
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CourseCreate'
|
||||
responses:
|
||||
201:
|
||||
description: 已创建
|
||||
|
||||
/api/v1/courses/{id}:
|
||||
get:
|
||||
summary: 获取课程
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
404:
|
||||
description: 未找到
|
||||
put:
|
||||
summary: 更新课程(管理员)
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CourseCreate'
|
||||
responses:
|
||||
200:
|
||||
description: 已更新
|
||||
delete:
|
||||
summary: 删除课程(管理员)
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
204:
|
||||
description: 已删除
|
||||
|
||||
/api/v1/courses/{id}/materials:
|
||||
post:
|
||||
summary: 上传课程资料(管理员)
|
||||
tags: [课程]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
201:
|
||||
description: 已上传
|
||||
|
||||
/api/v1/courses/{id}/knowledge-points:
|
||||
get:
|
||||
summary: 获取课程知识点
|
||||
tags: [知识点]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/KnowledgePoint'
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
|
||||
schemas:
|
||||
Course:
|
||||
type: object
|
||||
properties:
|
||||
id: { type: integer }
|
||||
name: { type: string }
|
||||
description: { type: string }
|
||||
category: { type: string }
|
||||
status: { type: string }
|
||||
CourseCreate:
|
||||
type: object
|
||||
required: [name]
|
||||
properties:
|
||||
name: { type: string, minLength: 1 }
|
||||
description: { type: string }
|
||||
category: { type: string }
|
||||
KnowledgePoint:
|
||||
type: object
|
||||
properties:
|
||||
id: { type: integer }
|
||||
title: { type: string }
|
||||
course_id: { type: integer }
|
||||
22
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/checklist.md
Normal file
22
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/checklist.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Agent-Course 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `GET /api/v1/courses` 列表分页筛选(status/category)
|
||||
- [ ] `POST /api/v1/courses` 创建课程(管理员)
|
||||
- [ ] `GET /api/v1/courses/{id}` 详情
|
||||
- [ ] `PUT /api/v1/courses/{id}` 更新(管理员)
|
||||
- [ ] `DELETE /api/v1/courses/{id}` 删除(管理员)
|
||||
- [ ] `GET /api/v1/courses/{id}/knowledge-points` 知识点列表
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 登录必需;写操作需管理员
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
18
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/context.md
Normal file
18
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/context.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Agent-Course 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth(认证/权限)、User(操作者信息)、Dify(知识拆解)
|
||||
- 输出接口:课程与知识点 API/服务,供 Exam/Training/Analytics 使用
|
||||
|
||||
## 关键约束
|
||||
- 安全:所有写操作需管理员;资料上传校验扩展名/大小
|
||||
- 性能:课程列表分页查询 ≤ 300ms(本地);常用筛选字段建索引
|
||||
- 观测:课程发布/下架/资料变更记录结构化日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:`DIFY_API_BASE`、`DIFY_API_KEY`、`DIFY_EXAM_WORKFLOW_ID`、`DIFY_ASSESSMENT_WORKFLOW_ID`
|
||||
- 关联模型/表:`courses`、`course_materials`、`knowledge_points`、`growth_paths`
|
||||
17
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/examples/README.md
Normal file
17
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/examples/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Agent-Course 示例(最小)
|
||||
|
||||
- 创建课程:
|
||||
|
||||
```python
|
||||
# app/api/v1/courses.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_current_user, require_admin
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", dependencies=[Depends(require_admin)])
|
||||
async def create_course():
|
||||
# 省略业务逻辑
|
||||
return ResponseModel(code=201, message="created")
|
||||
```
|
||||
46
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/prompt.md
Normal file
46
docs/规划/后端开发拆分策略/子agent/03-Agent-Course/prompt.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Agent-Course 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:课程管理(课程 CRUD、资料上传、知识点管理、成长路径)
|
||||
- 依赖模块:Auth、User、Dify
|
||||
- 对外输出:课程与知识点 API,供 Exam/Training/Analytics 使用
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/courses.py`、`app/services/course_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(读需登录,写需管理员)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
|
||||
## 可复用资产与迁移要点(与课程对话)
|
||||
- 网关复用(委托 08-Agent-Coze)
|
||||
- “与课程对话”前后端不在本模块内直接集成 Coze,而是通过 `Agent-Coze` 网关对接;本模块只负责课程/资料/知识点数据与权限。
|
||||
- 当需要在课程详情页开启对话时:由前端调 `POST /api/v1/course-chat/sessions` 创建对话会话,并将 `course_id` 透传给网关,用于选择对应 Bot 或上下文装载。
|
||||
- 前端可复用(`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-frontend/`)
|
||||
- 页面:`src/pages/NewChat/*` 与 `src/pages/Exam/*`(含卡片结果展示)可复用到课程对话 UI;仅需替换为新网关端点并绑定课程上下文。
|
||||
- API:`src/server/api.ts`/`global.ts` 的流式聊天、会话管理与中断封装;迁移时对齐 `POST /api/v1/course-chat/sessions`,并按需扩展 `POST /api/v1/course-chat/messages` 或 `WS /ws/v1/course-chat/{session_id}`(若启用流式/语音)。
|
||||
- 卡片渲染:保留现有对 `content_type == "card"` 的分支显示(与 Exam 复用同一渲染);由网关进行卡片判定与透传。
|
||||
- 后端参考(`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-backend/`)
|
||||
- `main.py` 中的 SSE 事件流与卡片检测逻辑可在 `Agent-Coze` 实现侧复用;本模块仅消费其网关能力,不直接依赖 Coze SDK。
|
||||
- 配置与安全
|
||||
- 前端统一走 Auth 的 Bearer 鉴权;不在课程模块暴露任何 Coze 凭据。
|
||||
- 课程数据的权限/审计在本模块内完成;对话的认证与限流在网关侧处理。
|
||||
|
||||
## 整合并入系统(当前阶段)
|
||||
- 后端
|
||||
- 仅负责课程/资料/知识点/权限;“与课程对话”经 `08-Agent-Coze` 网关实现(课程 ID/上下文装载 → 选择 Bot/上下文注入)。
|
||||
- 端点:`POST /api/v1/course-chat/sessions`、`/messages(stream)`;旧 `/api/*` 由网关短期兼容转发。
|
||||
- 前端
|
||||
- 在课程详情页通过子应用或 `<iframe>` 挂载 `/ai-chat/newChat?course_id=...`,共享鉴权与 API 基址到新网关。
|
||||
- 验证 SSE 流与卡片渲染在课程上下文下工作正常。
|
||||
- 验收
|
||||
- 课程页可稳定开启对话,基础流程打通并通过本地联调。
|
||||
104
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/api_contract.yaml
Normal file
104
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/api_contract.yaml
Normal file
@@ -0,0 +1,104 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 考试模块API
|
||||
version: 1.0.0
|
||||
description: 动态考试与成绩的最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/exams/start:
|
||||
post:
|
||||
summary: 开始考试
|
||||
tags: [考试]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [course_id]
|
||||
properties:
|
||||
course_id: { type: integer }
|
||||
count: { type: integer, minimum: 1, maximum: 100, default: 10 }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: { type: integer, example: 200 }
|
||||
message: { type: string, example: success }
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
exam_id: { type: integer }
|
||||
|
||||
/api/v1/exams/submit:
|
||||
post:
|
||||
summary: 提交答案
|
||||
tags: [考试]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [exam_id, answers]
|
||||
properties:
|
||||
exam_id: { type: integer }
|
||||
answers:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
question_id: { type: string }
|
||||
answer: { type: string }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
/api/v1/exams/{id}:
|
||||
get:
|
||||
summary: 获取考试详情
|
||||
tags: [考试]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
404:
|
||||
description: 未找到
|
||||
|
||||
/api/v1/exams/records:
|
||||
get:
|
||||
summary: 考试记录
|
||||
tags: [考试]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: query
|
||||
name: page
|
||||
schema: { type: integer, minimum: 1, default: 1 }
|
||||
- in: query
|
||||
name: size
|
||||
schema: { type: integer, minimum: 1, maximum: 100, default: 10 }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
20
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/checklist.md
Normal file
20
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/checklist.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Agent-Exam 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `POST /api/v1/exams/start` 动态组卷(Dify)
|
||||
- [ ] `POST /api/v1/exams/submit` 提交判题,生成成绩
|
||||
- [ ] `GET /api/v1/exams/{id}` 考试详情
|
||||
- [ ] `GET /api/v1/exams/records` 考试记录分页
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 登录必需;题目与答案分离存储;防重放
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
18
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/context.md
Normal file
18
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/context.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Agent-Exam 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth(认证)、User(考生信息)、Course(课程/知识点)、Dify(动态组卷)
|
||||
- 输出接口:考试与成绩 API/服务,供 Analytics 消费
|
||||
|
||||
## 关键约束
|
||||
- 安全:登录必需;题目与答案分离存储;防重放
|
||||
- 性能:试题生成/提交 ≤ 500ms(本地);记录分页查询 ≤ 300ms
|
||||
- 观测:开始/提交/判题/报告生成记录结构化日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:`DIFY_API_BASE`、`DIFY_API_KEY`、`DIFY_EXAM_WORKFLOW_ID`
|
||||
- 关联模型/表:`exam_sessions`、`exam_questions`、`exam_answers`、`exam_results`、`mistakes`
|
||||
17
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/examples/README.md
Normal file
17
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/examples/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Agent-Exam 示例(最小)
|
||||
|
||||
- 开始考试:
|
||||
|
||||
```python
|
||||
# app/api/v1/exams.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_current_user
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/start")
|
||||
async def start_exam():
|
||||
# 省略 Dify 动态组卷逻辑
|
||||
return ResponseModel(code=200, message="success", data={"exam_id": 1})
|
||||
```
|
||||
22
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/prompt.md
Normal file
22
docs/规划/后端开发拆分策略/子agent/04-Agent-Exam/prompt.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Agent-Exam 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:考试(动态试题、流程管理、判题与成绩、错题管理、报告)
|
||||
- 依赖模块:Auth、User、Course、Dify
|
||||
- 对外输出:考试与成绩 API,供 Analytics 使用
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/exams.py`、`app/services/exam_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(读需登录,写需登录)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
60
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/api_contract.yaml
Normal file
60
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/api_contract.yaml
Normal file
@@ -0,0 +1,60 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: AI陪练模块API
|
||||
version: 1.0.0
|
||||
description: 陪练场景与会话的最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/training-scenes:
|
||||
get:
|
||||
summary: 陪练场景列表
|
||||
tags: [陪练]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
post:
|
||||
summary: 创建场景(管理员)
|
||||
tags: [陪练]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
201:
|
||||
description: 已创建
|
||||
|
||||
/api/v1/training/start:
|
||||
post:
|
||||
summary: 开始陪练
|
||||
tags: [陪练]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [scene_id]
|
||||
properties:
|
||||
scene_id: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
/api/v1/training/end:
|
||||
post:
|
||||
summary: 结束陪练
|
||||
tags: [陪练]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
20
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/checklist.md
Normal file
20
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/checklist.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Agent-Training 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `GET /api/v1/training-scenes` 场景列表
|
||||
- [ ] `POST /api/v1/training-scenes` 创建场景(管理员)
|
||||
- [ ] `POST /api/v1/training/start` 开始陪练(创建会话/初始化 Coze)
|
||||
- [ ] `POST /api/v1/training/end` 结束陪练(生成报告)
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 登录必需;会话鉴权;敏感音频访问控制
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
18
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/context.md
Normal file
18
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/context.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Agent-Training 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth(认证)、User(学员信息)、Course(课程内容)、Coze(对话/评分)
|
||||
- 输出接口:陪练会话/记录/报告 API/服务,供 Analytics 消费
|
||||
|
||||
## 关键约束
|
||||
- 安全:登录必需;会话鉴权;敏感音频存储与访问控制
|
||||
- 性能:WS 往返延迟 < 100ms(本地);音频处理 < 500ms
|
||||
- 观测:会话开始/结束、评分生成记录结构化日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:`COZE_API_BASE`、`COZE_API_TOKEN`、`COZE_TRAINING_BOT_ID`
|
||||
- 关联模型/表:`training_scenes`、`training_sessions`、`training_messages`、`training_reports`
|
||||
17
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/examples/README.md
Normal file
17
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/examples/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Agent-Training 示例(最小)
|
||||
|
||||
- 开始陪练:
|
||||
|
||||
```python
|
||||
# app/api/v1/training.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_current_user
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/start")
|
||||
async def start_training():
|
||||
# 省略 Coze 会话初始化逻辑
|
||||
return ResponseModel(code=200, message="success")
|
||||
```
|
||||
50
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/prompt.md
Normal file
50
docs/规划/后端开发拆分策略/子agent/05-Agent-Training/prompt.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Agent-Training 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:AI 陪练(场景/会话管理、实时对话、评估报告)
|
||||
- 依赖模块:Auth、User、Course、Coze
|
||||
- 对外输出:陪练会话/记录/报告 API,供 Analytics 使用
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/training.py`、`app/services/training_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(读需登录,写需登录)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
|
||||
## 可复用资产与迁移要点
|
||||
- 后端对接(复用 08-Agent-Coze 网关)
|
||||
- 训练会话创建/结束:经 `Agent-Coze` 网关落到 Coze 客户端;与本模块的场景/记录模型解耦(Training 只持久化业务字段与审计,Coze 会话 ID 作为外部引用)。
|
||||
- 语音与流式:复用 `coze-chat-backend/main.py` 的 SSE 流式实现与中断逻辑(`conversation.message.delta/completed/failed`),保持“卡片”输出兼容(如需要在陪练中输出富结果)。
|
||||
- 上传能力:复用 `upload-file` 端点与文件到 Coze 的上传流程;在本模块内记录附件元数据与权限。
|
||||
- 前端可复用(`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-frontend/`)
|
||||
- 页面:`src/pages/Training/VoiceChat.tsx`、`src/pages/Training/TextChat.tsx`、`src/pages/Training/index.tsx` 可直接参考迁移;只需切换到新网关端点并接入统一鉴权。
|
||||
- Store:`src/stores/TrainingStore.ts` 的状态流转(连接/断开/中断/首个 delta 标记)、流式累计、滚动到底等逻辑可复用。
|
||||
- API:`src/server/api.ts`/`global.ts` 的会话/流式/中断接口封装;迁移时对齐为 `api_contract.yaml` 的 `POST /api/v1/training/sessions`、`POST /api/v1/training/sessions/{id}/end`,并预留 WS 能力(如需实时语音)。
|
||||
- 映射建议(旧 → 新)
|
||||
- 会话创建:`POST /agent/v1/cozechat/create-conversation` → `POST /api/v1/training/sessions`
|
||||
- 会话结束:无统一端点 → `POST /api/v1/training/sessions/{id}/end`
|
||||
- 流式聊天:`POST /agent/v1/cozechat/chat-stream` 或 `/api/chat/stream` → 由网关内聚合为会话内消息事件(如扩展 `WS /ws/v1/training/{session_id}`)。
|
||||
- 配置与安全
|
||||
- 使用 Auth 的 Bearer 认证;前端本地调试的 PAT 获取接口在生产禁用。
|
||||
- 复用 `COZE_API_BASE/WORKSPACE_ID` 等变量;保持 `NO_PROXY` 直连。
|
||||
|
||||
## 整合并入系统(当前阶段)
|
||||
- 后端并入
|
||||
- 依赖 `08-Agent-Coze` 网关:Training 仅持久化训练场景/记录/报告与审计字段,引用外部 `coze_conversation_id`;对话/中断/上传经网关转发。
|
||||
- 端点以本模块 `api_contract.yaml` 为准(`POST /api/v1/training/sessions`、`POST /api/v1/training/sessions/{id}/end`、`/messages(stream)`);旧路由由网关短期兼容。
|
||||
- 统一日志/鉴权/限流;SSE 错误映射为统一异常码。
|
||||
- 前端接入
|
||||
- 将 `coze-chat-frontend` 的 Training 页面以子应用挂载至主站(如 `/training/*`),统一登录态与 API 基址到新网关。
|
||||
- 验证语音/文本陪练的 SSE 流与中断在本地正常工作。
|
||||
- 验收
|
||||
- 后端端点通过集成测试;前端子应用在本地环境可稳定使用。
|
||||
55
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/api_contract.yaml
Normal file
55
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/api_contract.yaml
Normal file
@@ -0,0 +1,55 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 数据分析模块API
|
||||
version: 1.0.0
|
||||
description: 分析与报表最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/analytics/overview:
|
||||
get:
|
||||
summary: 数据总览
|
||||
tags: [分析]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
/api/v1/analytics/users/{id}/ability:
|
||||
get:
|
||||
summary: 个人能力雷达
|
||||
tags: [分析]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
404:
|
||||
description: 未找到
|
||||
|
||||
/api/v1/analytics/teams/{id}/overview:
|
||||
get:
|
||||
summary: 团队概况
|
||||
tags: [分析]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: integer }
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
19
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/checklist.md
Normal file
19
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/checklist.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Agent-Analytics 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `GET /api/v1/analytics/overview` 总览
|
||||
- [ ] `GET /api/v1/analytics/users/{id}/ability` 个人能力
|
||||
- [ ] `GET /api/v1/analytics/teams/{id}/overview` 团队概况
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 登录必需;团队/全局需管理员
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
18
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/context.md
Normal file
18
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/context.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Agent-Analytics 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:User(组织/成员)、Course(课程)、Exam(成绩)、Training(陪练记录)
|
||||
- 输出接口:个人/团队能力概览、趋势、报表 API
|
||||
|
||||
## 关键约束
|
||||
- 安全:登录必需;管理员可访问团队/全局数据
|
||||
- 性能:聚合查询缓存(Redis),热点数据 TTL 5-10 分钟
|
||||
- 观测:耗时聚合打点记录(指标与标签)
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:复用通用 `.env`
|
||||
- 关联模型/表:`analytics_snapshots`、`user_metrics`、`team_metrics`、`reports`
|
||||
@@ -0,0 +1,17 @@
|
||||
# Agent-Analytics 示例(最小)
|
||||
|
||||
- 个人能力:
|
||||
|
||||
```python
|
||||
# app/api/v1/analytics.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_current_user
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/users/{user_id}/ability")
|
||||
async def user_ability(user_id: int):
|
||||
# 省略聚合逻辑
|
||||
return ResponseModel(code=200, message="success", data={"communication": 85})
|
||||
```
|
||||
22
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/prompt.md
Normal file
22
docs/规划/后端开发拆分策略/子agent/06-Agent-Analytics/prompt.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Agent-Analytics 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:学习与陪练数据聚合、能力评估、趋势与报表
|
||||
- 依赖模块:Auth、User、Course、Exam、Training
|
||||
- 对外输出:个人/团队分析、趋势数据、报表生成 API
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/analytics.py`、`app/services/analytics_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(读需登录)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
50
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/api_contract.yaml
Normal file
50
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/api_contract.yaml
Normal file
@@ -0,0 +1,50 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 系统管理模块API
|
||||
version: 1.0.0
|
||||
description: 管理与监控最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/admin/settings:
|
||||
get:
|
||||
summary: 获取系统设置
|
||||
tags: [管理]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
put:
|
||||
summary: 更新系统设置(管理员)
|
||||
tags: [管理]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 已更新
|
||||
|
||||
/api/v1/admin/health:
|
||||
get:
|
||||
summary: 健康检查
|
||||
tags: [管理]
|
||||
responses:
|
||||
200:
|
||||
description: 健康
|
||||
|
||||
/api/v1/admin/metrics:
|
||||
get:
|
||||
summary: 系统指标
|
||||
tags: [管理]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: 成功
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
|
||||
21
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/checklist.md
Normal file
21
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/checklist.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Agent-Admin 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `GET /api/v1/admin/settings` 获取系统设置
|
||||
- [ ] `PUT /api/v1/admin/settings` 更新设置(管理员,留审计)
|
||||
- [ ] `GET /api/v1/admin/health` 健康检查
|
||||
- [ ] `GET /api/v1/admin/metrics` 指标
|
||||
|
||||
## 安全与规范
|
||||
- [ ] 仅管理员可写;敏感配置加密;操作审计
|
||||
- [ ] 参数验证与统一异常
|
||||
- [ ] 结构化日志覆盖关键操作
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
|
||||
19
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/context.md
Normal file
19
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/context.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Agent-Admin 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/api/v1/`、`app/services/`、`app/models/`、`app/schemas/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth(管理员认证与授权)、User(岗位/成员)
|
||||
- 输出接口:系统设置、岗位、日志、健康、指标 API
|
||||
|
||||
## 关键约束
|
||||
- 安全:仅管理员可写;敏感配置加密;操作留审计
|
||||
- 性能:健康/指标接口实时性;日志分页查询优化
|
||||
- 观测:配置变更、岗位权限调整写结构化审计日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:复用通用 `.env`
|
||||
- 关联模型/表:`system_configs`、`positions`、`operation_logs`、`system_metrics`
|
||||
|
||||
15
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/examples/README.md
Normal file
15
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/examples/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Agent-Admin 示例(最小)
|
||||
|
||||
- 健康检查:
|
||||
|
||||
```python
|
||||
# app/api/v1/admin.py 片段(示例)
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
```
|
||||
|
||||
22
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/prompt.md
Normal file
22
docs/规划/后端开发拆分策略/子agent/07-Agent-Admin/prompt.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Agent-Admin 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:系统配置、岗位权限、日志与健康监控、备份
|
||||
- 依赖模块:Auth、User
|
||||
- 对外输出:系统设置/岗位/日志/健康/指标 API
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/api/v1/admin.py`、`app/services/admin_service.py`、相关 `app/models/`、`app/schemas/`
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 仅管理员可调用写操作,变更留审计
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
67
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/api_contract.yaml
Normal file
67
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/api_contract.yaml
Normal file
@@ -0,0 +1,67 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: Coze 网关API
|
||||
version: 1.0.0
|
||||
description: 课程对话与陪练网关最小契约(骨架)
|
||||
|
||||
paths:
|
||||
/api/v1/course-chat/sessions:
|
||||
post:
|
||||
summary: 创建课程对话会话
|
||||
tags: [Coze]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [course_id]
|
||||
properties:
|
||||
course_id: { type: integer }
|
||||
responses:
|
||||
201:
|
||||
description: 已创建
|
||||
|
||||
/api/v1/training/sessions:
|
||||
post:
|
||||
summary: 创建陪练会话
|
||||
tags: [Coze]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [scene_id]
|
||||
properties:
|
||||
scene_id: { type: integer }
|
||||
responses:
|
||||
201:
|
||||
description: 已创建
|
||||
|
||||
/api/v1/training/sessions/{id}/end:
|
||||
post:
|
||||
summary: 结束陪练会话
|
||||
tags: [Coze]
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: string }
|
||||
responses:
|
||||
200:
|
||||
description: 已结束
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
|
||||
19
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/checklist.md
Normal file
19
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/checklist.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Agent-Coze 开发检查清单(简版)
|
||||
|
||||
## 准备
|
||||
- [ ] 阅读通用规范与架构文档
|
||||
|
||||
## 最小功能
|
||||
- [ ] `POST /api/v1/course-chat/sessions` 创建课程对话会话
|
||||
- [ ] `POST /api/v1/training/sessions` 创建陪练会话
|
||||
- [ ] `POST /api/v1/training/sessions/{id}/end` 结束陪练会话
|
||||
|
||||
## 稳定性与安全
|
||||
- [ ] 登录必需;会话鉴权;限流/重试/超时
|
||||
- [ ] 外部调用错误转换为统一异常;结构化日志记录
|
||||
|
||||
## 质量
|
||||
- [ ] 单元测试覆盖率 ≥ 80%
|
||||
- [ ] 通过 Black/isort/flake8/mypy
|
||||
- [ ] API 与 `api_contract.yaml` 一致
|
||||
|
||||
19
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/context.md
Normal file
19
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/context.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Agent-Coze 上下文(极简版)
|
||||
|
||||
## 位置
|
||||
- 项目根:`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
- 工作目录:`app/services/ai/coze/`、`app/api/v1/`
|
||||
|
||||
## 依赖
|
||||
- 输入依赖:Auth(认证)
|
||||
- 输出接口:课程对话与陪练相关 API/服务,供 Course/Training/Analytics 使用
|
||||
|
||||
## 关键约束
|
||||
- 安全:登录必需;会话鉴权;限流/重试/超时
|
||||
- 性能:流式响应及时性;API 限速与退避
|
||||
- 观测:外部调用成功率/延迟/错误率指标与日志
|
||||
|
||||
## 最小运行信息
|
||||
- 环境变量:`COZE_API_BASE`、`COZE_WORKSPACE_ID`、`COZE_API_TOKEN`、`COZE_TRAINING_BOT_ID`、`COZE_CHAT_BOT_ID`
|
||||
- 关联目录:`app/services/ai/coze/`(client、models、exceptions)
|
||||
|
||||
17
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/examples/README.md
Normal file
17
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/examples/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Agent-Coze 示例(最小)
|
||||
|
||||
- 创建陪练会话:
|
||||
|
||||
```python
|
||||
# app/api/v1/training_gateway.py 片段(示例)
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.schemas.base import ResponseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/training/sessions")
|
||||
async def create_training_session():
|
||||
# 省略 coze 客户端调用
|
||||
return ResponseModel(code=201, message="created")
|
||||
```
|
||||
|
||||
54
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/prompt.md
Normal file
54
docs/规划/后端开发拆分策略/子agent/08-Agent-Coze/prompt.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Agent-Coze 提示词(极简版)
|
||||
|
||||
## 必读引用
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
|
||||
## 你的角色
|
||||
- 本模块职责:封装 Coze 客户端(会话/消息/流式),支撑陪练与课程对话
|
||||
- 依赖模块:Auth
|
||||
- 对外输出:课程对话与陪练网关 API(供前端与第三方解耦)
|
||||
|
||||
## 交付内容
|
||||
- 代码:`app/services/ai/coze/` 下客户端与服务;`app/api/v1/` 网关路由
|
||||
- 契约:本目录 `api_contract.yaml`(OpenAPI 3.0)
|
||||
- 文档与测试:`checklist.md` 全通过,单元测试覆盖率 ≥ 80%
|
||||
|
||||
## 验收标准(最小集)
|
||||
- API 与 `api_contract.yaml` 一致并通过基本集成测试
|
||||
- 认证/权限依赖正常(读写需登录)
|
||||
- 输入校验、统一异常、结构化日志符合通用规范
|
||||
|
||||
## 可复用资产与迁移要点
|
||||
- 后端可复用(`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-backend/`)
|
||||
- 认证封装:`auth.py` 的 `CozeAuthManager`(优先 JWT,fallback PAT;自动设置 `NO_PROXY` 直连 `*.coze.cn`)。建议直接复用到 `app/services/ai/coze/client.py` 或在依赖注入处统一获取 `Coze` 客户端。
|
||||
- 流式聊天与卡片输出:`main.py` 中 SSE 事件流(`conversation.message.delta/completed` 等)及对 `card_type` 的检测(将 `content_type` 标识为 `card`)可原样迁移,支撑动态考题与课程对话的“卡片”富结果。
|
||||
- 会话管理与上传:`/api/conversations` 创建/删除、`/agent/v1/cozechat/create-conversation` 兼容端点、`/agent/v1/cozechat/upload-file` 文件上传,均可作为本模块网关能力的底层实现。
|
||||
- 兼容端点保留策略:现有 `/agent/v1/cozechat/*` 可经由本模块网关路由转发,逐步收敛至 `api_contract.yaml` 形态。
|
||||
- 网关映射(旧 → 新)
|
||||
- 课程对话创建:旧 `POST /api/conversations` 或 `GET /agent/v1/cozechat/create-conversation` → 新 `POST /api/v1/course-chat/sessions`
|
||||
- 陪练会话创建:旧 `POST /agent/v1/cozechat/create-conversation` → 新 `POST /api/v1/training/sessions`
|
||||
- 陪练会话结束:旧无统一端点 → 新 `POST /api/v1/training/sessions/{id}/end`
|
||||
- 可按需扩展:`POST /api/v1/course-chat/messages`(发送/流式)、`WS /ws/v1/*`(文本/语音)。若扩展,请同步更新本目录 `api_contract.yaml`。
|
||||
- 前端可复用(`/Users/nongjun/Desktop/Ai公司/本地开发与测试/coze-chat-frontend/`)
|
||||
- 页面与逻辑:`src/pages/Training/*`(语音/文本陪练)、`src/pages/NewChat/*`(通用对话)、`src/pages/Exam/*`(动态考题)可直接参考;保留 SSE 解析与“卡片”渲染分支。
|
||||
- API 封装:`src/server/api.ts`、`src/server/global.ts` 中的会话/聊天/上传请求与中断逻辑;迁移时仅需切换到本模块网关的新端点。
|
||||
- Store 模式:`src/stores/*Store.ts` 的流式拼接、滚动、失败重试与中断处理可复用。
|
||||
- 配置与安全
|
||||
- 环境变量:复用 `COZE_API_BASE`、`COZE_WORKSPACE_ID`、`COZE_API_TOKEN` 或 OAuth 三件套(`COZE_OAUTH_CLIENT_ID`、`COZE_OAUTH_PUBLIC_KEY_ID`、`COZE_OAUTH_PRIVATE_KEY_PATH`)。
|
||||
- 认证:对外统一走 Auth 的 Bearer 鉴权;前端“开发用 PAT 获取”接口仅限本地调试,生产关闭。
|
||||
- 稳定性与观测
|
||||
- 为外部调用加入限流/超时/重试与断路器;将 Coze 错误映射为统一异常;输出结构化日志与成功率/延迟/错误率指标(按通用规范)。
|
||||
|
||||
## 整合并入系统(当前阶段)
|
||||
- 后端并入(立即执行)
|
||||
- 新建 `app/services/ai/coze/{client.py,service.py,exceptions.py,models.py}`,迁移认证(OAuth 优先、PAT 回退、`NO_PROXY` 直连)与 SSE/卡片/中断实现。
|
||||
- 新建 `app/api/v1/coze_gateway.py`,按本目录 `api_contract.yaml` 提供路由;短期保留 `/agent/v1/cozechat/*`、`/api/*` 兼容转发。
|
||||
- 统一鉴权(Bearer)、环境变量与结构化日志;将 SDK 错误映射为统一异常;外部调用加限流/超时/重试。
|
||||
- 前端接入(立即执行)
|
||||
- 将 `coze-chat-frontend` 以子应用挂载到主站(如 `/ai-chat/*`),复用现有页面与 Store;仅切换 API 基址到新网关,复用主站登录态。
|
||||
- 验证 SSE 流消息、卡片消息渲染与“中断”动作在本地 `localhost` 正常工作。
|
||||
- 验收
|
||||
- 新网关端点可用并通过基本集成测试;子应用集成后在本地环境稳定运行。
|
||||
43
docs/规划/后端开发拆分策略/子agent/README.md
Normal file
43
docs/规划/后端开发拆分策略/子agent/README.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# 子Agent工作包
|
||||
|
||||
本目录包含所有子Agent的独立工作包,每个Agent都有自己的提示词、上下文和工作指南。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
子agent/
|
||||
├── 00-通用基础/ # 所有Agent共享的基础信息
|
||||
├── 01-Agent-Auth/ # 认证授权模块
|
||||
├── 02-Agent-User/ # 用户管理模块
|
||||
├── 03-Agent-Course/ # 课程管理模块
|
||||
├── 04-Agent-Exam/ # 考试模块
|
||||
├── 05-Agent-Training/ # AI陪练模块
|
||||
├── 06-Agent-Analytics/ # 数据分析模块
|
||||
├── 07-Agent-Admin/ # 系统管理模块
|
||||
├── 08-Agent-Coze/ # Coze集成服务
|
||||
└── 09-Agent-Dify/ # Dify集成服务
|
||||
```
|
||||
|
||||
## 每个Agent包含的文件
|
||||
|
||||
1. **prompt.md** - Agent的完整提示词
|
||||
2. **context.md** - 必要的上下文信息
|
||||
3. **api_contract.yaml** - API接口契约
|
||||
4. **dependencies.md** - 依赖关系说明
|
||||
5. **examples/** - 示例代码目录
|
||||
6. **checklist.md** - 开发检查清单
|
||||
7. **test_scenarios.md** - 测试场景
|
||||
|
||||
## 使用方法
|
||||
|
||||
1. 将整个Agent文件夹复制到Cursor的background云端
|
||||
2. 在Cursor中创建新的Agent,使用prompt.md作为系统提示词
|
||||
3. 根据context.md了解项目背景
|
||||
4. 按照checklist.md进行开发
|
||||
5. 参考examples目录的示例代码
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 所有文件路径都使用相对路径
|
||||
- 确保引用的文件都包含在Agent文件夹中
|
||||
- 定期更新各Agent的文档以保持同步
|
||||
154
docs/规划/后端开发拆分策略/子agent/package_agent.sh
Executable file
154
docs/规划/后端开发拆分策略/子agent/package_agent.sh
Executable file
@@ -0,0 +1,154 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Agent打包脚本 - 用于快速打包某个Agent的所有文件
|
||||
|
||||
# 颜色定义
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# 显示使用说明
|
||||
show_usage() {
|
||||
echo "使用方法: ./package_agent.sh [Agent编号或名称]"
|
||||
echo ""
|
||||
echo "示例:"
|
||||
echo " ./package_agent.sh 01"
|
||||
echo " ./package_agent.sh Auth"
|
||||
echo " ./package_agent.sh 01-Agent-Auth"
|
||||
echo ""
|
||||
echo "可用的Agent:"
|
||||
ls -d [0-9][0-9]-Agent-* 2>/dev/null | sed 's/^/ /'
|
||||
}
|
||||
|
||||
# 检查参数
|
||||
if [ -z "$1" ]; then
|
||||
show_usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 查找Agent目录
|
||||
AGENT_DIR=""
|
||||
SEARCH_TERM=$1
|
||||
|
||||
# 尝试不同的匹配方式
|
||||
if [ -d "$SEARCH_TERM" ]; then
|
||||
AGENT_DIR="$SEARCH_TERM"
|
||||
elif [ -d "[0-9][0-9]-Agent-$SEARCH_TERM" ]; then
|
||||
AGENT_DIR=$(ls -d [0-9][0-9]-Agent-$SEARCH_TERM 2>/dev/null | head -1)
|
||||
elif [ -d "$SEARCH_TERM-Agent-"* ]; then
|
||||
AGENT_DIR=$(ls -d $SEARCH_TERM-Agent-* 2>/dev/null | head -1)
|
||||
else
|
||||
# 模糊匹配
|
||||
AGENT_DIR=$(ls -d *-Agent-*$SEARCH_TERM* 2>/dev/null | head -1)
|
||||
fi
|
||||
|
||||
# 检查是否找到目录
|
||||
if [ -z "$AGENT_DIR" ] || [ ! -d "$AGENT_DIR" ]; then
|
||||
echo -e "${RED}错误: 找不到Agent目录 '$SEARCH_TERM'${NC}"
|
||||
echo ""
|
||||
show_usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}找到Agent目录: $AGENT_DIR${NC}"
|
||||
|
||||
# 创建输出目录
|
||||
OUTPUT_DIR="packaged"
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
|
||||
# 生成输出文件名
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
OUTPUT_FILE="$OUTPUT_DIR/${AGENT_DIR}_${TIMESTAMP}.tar.gz"
|
||||
|
||||
# 创建临时目录
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
PACKAGE_DIR="$TEMP_DIR/$AGENT_DIR"
|
||||
mkdir -p "$PACKAGE_DIR"
|
||||
|
||||
# 复制Agent文件
|
||||
echo "正在打包Agent文件..."
|
||||
cp -r "$AGENT_DIR"/* "$PACKAGE_DIR/" 2>/dev/null
|
||||
|
||||
# 复制通用基础文件
|
||||
echo "添加通用基础文件..."
|
||||
mkdir -p "$PACKAGE_DIR/00-通用基础"
|
||||
cp -r "00-通用基础"/* "$PACKAGE_DIR/00-通用基础/" 2>/dev/null
|
||||
|
||||
# 添加项目脚手架的关键文件引用
|
||||
echo "添加项目基础代码引用..."
|
||||
mkdir -p "$PACKAGE_DIR/_project_base"
|
||||
cat > "$PACKAGE_DIR/_project_base/README.md" << EOF
|
||||
# 项目基础代码引用
|
||||
|
||||
这些是项目脚手架中的关键文件,Agent开发时需要参考:
|
||||
|
||||
## 基础模型
|
||||
- app/models/base.py - BaseModel, SoftDeleteMixin, AuditMixin
|
||||
- app/schemas/base.py - BaseSchema, ResponseModel, PageModel
|
||||
|
||||
## 核心功能
|
||||
- app/core/exceptions.py - 统一异常处理
|
||||
- app/core/logger.py - 日志配置
|
||||
- app/core/middleware.py - 中间件定义
|
||||
- app/config/settings.py - 系统配置
|
||||
|
||||
## 开发规范
|
||||
请查看 00-通用基础/base_prompt.md 了解详细的开发规范。
|
||||
EOF
|
||||
|
||||
# 添加快速启动脚本
|
||||
cat > "$PACKAGE_DIR/START_HERE.md" << EOF
|
||||
# $AGENT_DIR 快速启动指南
|
||||
|
||||
## 1. 了解你的角色
|
||||
请先阅读 \`prompt.md\` 了解你的职责和任务。
|
||||
|
||||
## 2. 理解项目上下文
|
||||
查看 \`context.md\` 了解项目结构和依赖关系。
|
||||
|
||||
## 3. 查看API规范
|
||||
如果有 \`api_contract.yaml\`,请仔细阅读API接口定义。
|
||||
|
||||
## 4. 参考示例代码
|
||||
查看 \`examples/\` 目录中的示例代码。
|
||||
|
||||
## 5. 遵循开发规范
|
||||
务必遵循 \`00-通用基础/base_prompt.md\` 中的规范。
|
||||
|
||||
## 6. 使用检查清单
|
||||
按照 \`checklist.md\` 进行开发和自检。
|
||||
|
||||
## 开始开发
|
||||
\`\`\`
|
||||
我是$AGENT_DIR,准备开始开发工作。
|
||||
我已经阅读了所有相关文档,理解了我的职责。
|
||||
请确认项目根目录路径,我将开始创建代码。
|
||||
\`\`\`
|
||||
EOF
|
||||
|
||||
# 创建压缩包
|
||||
cd "$TEMP_DIR"
|
||||
tar -czf "$OUTPUT_FILE" "$AGENT_DIR"
|
||||
cd - > /dev/null
|
||||
|
||||
# 清理临时文件
|
||||
rm -rf "$TEMP_DIR"
|
||||
|
||||
# 显示结果
|
||||
echo -e "${GREEN}✅ 打包完成!${NC}"
|
||||
echo -e "输出文件: ${YELLOW}$OUTPUT_FILE${NC}"
|
||||
echo -e "文件大小: $(du -h "$OUTPUT_FILE" | cut -f1)"
|
||||
echo ""
|
||||
echo "你可以:"
|
||||
echo "1. 将此文件上传到Cursor云端"
|
||||
echo "2. 解压后在本地Cursor中使用"
|
||||
echo "3. 分享给其他开发者"
|
||||
|
||||
# 显示包含的文件
|
||||
echo ""
|
||||
echo "包含的文件:"
|
||||
tar -tzf "$OUTPUT_FILE" | head -20
|
||||
if [ $(tar -tzf "$OUTPUT_FILE" | wc -l) -gt 20 ]; then
|
||||
echo "... 以及更多文件"
|
||||
fi
|
||||
21
docs/规划/后端开发拆分策略/子agent/prompt_template.md
Normal file
21
docs/规划/后端开发拆分策略/子agent/prompt_template.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Agent提示词模板
|
||||
|
||||
## 基础规范
|
||||
**重要**: 你必须先阅读并严格遵循 `00-通用基础/base_prompt.md` 中的所有开发规范。
|
||||
|
||||
## 你的角色
|
||||
[具体角色描述]
|
||||
|
||||
## 核心职责
|
||||
[职责列表]
|
||||
|
||||
## 依赖说明
|
||||
[依赖关系]
|
||||
|
||||
## 开发要求
|
||||
在开发过程中,请确保:
|
||||
1. 遵循 `00-通用基础/base_prompt.md` 中的代码规范
|
||||
2. 参考 `00-通用基础/project_structure.md` 了解项目结构
|
||||
3. 所有代码必须通过格式化、类型检查和测试
|
||||
|
||||
[其他内容...]
|
||||
70
docs/规划/后端开发拆分策略/子agent/test_agent_understanding.md
Normal file
70
docs/规划/后端开发拆分策略/子agent/test_agent_understanding.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Agent理解度测试清单
|
||||
|
||||
使用这个清单来验证Agent是否正确理解了项目上下文。
|
||||
|
||||
## 基础理解测试
|
||||
|
||||
### 1. 项目结构
|
||||
问:项目根目录在哪里?app目录下有哪些子目录?
|
||||
期望:能正确说出路径和主要目录结构
|
||||
|
||||
### 2. 开发规范
|
||||
问:导入语句应该如何排序?
|
||||
期望:标准库 -> 第三方库 -> 本地模块
|
||||
|
||||
### 3. 基础类
|
||||
问:数据库模型应该继承哪个基类?
|
||||
期望:BaseModel,可能还需要AuditMixin或SoftDeleteMixin
|
||||
|
||||
## 架构理解测试
|
||||
|
||||
### 4. 协作机制
|
||||
问:什么是GlobalContext?它的作用是什么?
|
||||
期望:能解释全局上下文的作用和使用方式
|
||||
|
||||
### 5. 模块边界
|
||||
问:你的模块可以直接访问其他模块的数据库表吗?
|
||||
期望:不可以,应该通过服务接口调用
|
||||
|
||||
### 6. 错误处理
|
||||
问:如何处理外部服务(如Coze)调用失败?
|
||||
期望:使用ExternalServiceError,包含重试机制
|
||||
|
||||
## 具体实现测试
|
||||
|
||||
### 7. API响应
|
||||
问:API响应应该使用什么格式?
|
||||
期望:使用ResponseModel包装,包含code、message、data
|
||||
|
||||
### 8. 依赖注入
|
||||
问:如何在API中获取当前用户?
|
||||
期望:使用Depends(get_current_user)
|
||||
|
||||
### 9. 日志记录
|
||||
问:如何记录一个用户登录事件?
|
||||
期望:使用logger.info(),包含结构化数据
|
||||
|
||||
### 10. 测试要求
|
||||
问:单元测试覆盖率要求是多少?
|
||||
期望:80%以上
|
||||
|
||||
## 评分标准
|
||||
- 10个全部正确:Agent完全理解项目
|
||||
- 8-9个正确:理解良好,可以开始开发
|
||||
- 6-7个正确:需要补充部分文档
|
||||
- 5个以下:需要重新引用完整文档
|
||||
|
||||
## 使用方法
|
||||
```
|
||||
请回答以下问题来验证你对项目的理解:
|
||||
1. 项目根目录在哪里?
|
||||
2. 导入语句应该如何排序?
|
||||
3. 数据库模型应该继承哪个基类?
|
||||
4. 什么是GlobalContext?
|
||||
5. 你的模块可以直接访问其他模块的数据库表吗?
|
||||
6. 如何处理外部服务调用失败?
|
||||
7. API响应应该使用什么格式?
|
||||
8. 如何在API中获取当前用户?
|
||||
9. 如何记录一个用户登录事件?
|
||||
10. 单元测试覆盖率要求是多少?
|
||||
```
|
||||
83
docs/规划/后端开发拆分策略/子agent/update_all_agents.sh
Executable file
83
docs/规划/后端开发拆分策略/子agent/update_all_agents.sh
Executable file
@@ -0,0 +1,83 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 更新所有Agent的context.md,添加规划文档引用
|
||||
|
||||
echo "开始更新所有Agent的context.md文件..."
|
||||
|
||||
# 要插入的内容
|
||||
DOCS_REFERENCE='## 重要规划文档
|
||||
在开始开发前,请确保你已经理解以下关键文档:
|
||||
- `../../协作机制设计.md` - 特别是全局上下文(GlobalContext)和服务间调用机制
|
||||
- `../../模块分工指南.md` - 了解本模块的职责边界
|
||||
- `../../开发规范文档.md` - 编码标准和API设计规范
|
||||
- `../../统一基础代码.md` - 可复用的代码模板
|
||||
|
||||
'
|
||||
|
||||
# 遍历所有Agent目录
|
||||
for agent_dir in [0-9][0-9]-Agent-*/; do
|
||||
if [ -d "$agent_dir" ]; then
|
||||
context_file="${agent_dir}context.md"
|
||||
|
||||
# 跳过已经更新过的(Auth)
|
||||
if [[ "$agent_dir" == "01-Agent-Auth/" ]]; then
|
||||
echo "跳过 $agent_dir (已更新)"
|
||||
continue
|
||||
fi
|
||||
|
||||
# 如果context.md不存在,创建它
|
||||
if [ ! -f "$context_file" ]; then
|
||||
echo "创建 $context_file"
|
||||
cat > "$context_file" << EOF
|
||||
# ${agent_dir%/} 上下文信息
|
||||
|
||||
$DOCS_REFERENCE
|
||||
## 项目位置
|
||||
|
||||
- 项目根目录: \`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/\`
|
||||
- 你的工作目录: [待补充]
|
||||
|
||||
## 依赖说明
|
||||
|
||||
[待补充]
|
||||
|
||||
## 相关文档
|
||||
|
||||
[待补充]
|
||||
EOF
|
||||
else
|
||||
# 如果存在,在文件开头添加文档引用
|
||||
echo "更新 $context_file"
|
||||
|
||||
# 检查是否已经包含规划文档引用
|
||||
if grep -q "重要规划文档" "$context_file"; then
|
||||
echo " 已包含规划文档引用,跳过"
|
||||
else
|
||||
# 创建临时文件
|
||||
temp_file=$(mktemp)
|
||||
|
||||
# 获取第一行(通常是标题)
|
||||
head -1 "$context_file" > "$temp_file"
|
||||
echo "" >> "$temp_file"
|
||||
|
||||
# 添加文档引用
|
||||
echo "$DOCS_REFERENCE" >> "$temp_file"
|
||||
|
||||
# 添加原文件的其余内容(跳过第一行)
|
||||
tail -n +2 "$context_file" >> "$temp_file"
|
||||
|
||||
# 替换原文件
|
||||
mv "$temp_file" "$context_file"
|
||||
echo " ✓ 已添加规划文档引用"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "更新完成!"
|
||||
echo ""
|
||||
echo "提示:"
|
||||
echo "1. 请检查生成的context.md文件"
|
||||
echo "2. 补充[待补充]的内容"
|
||||
echo "3. 根据每个Agent的特点调整文档引用"
|
||||
179
docs/规划/后端开发拆分策略/子agent/云端协作最佳实践.md
Normal file
179
docs/规划/后端开发拆分策略/子agent/云端协作最佳实践.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# 子Agent云端协作最佳实践
|
||||
|
||||
## 1. 工作包完整性建议
|
||||
|
||||
### 1.1 必要文件清单
|
||||
每个Agent文件夹应包含:
|
||||
- ✅ `prompt.md` - 完整的系统提示词
|
||||
- ✅ `context.md` - 项目上下文和依赖
|
||||
- ✅ `api_contract.yaml` - API接口定义
|
||||
- ✅ `checklist.md` - 开发检查清单
|
||||
- ✅ `examples/` - 示例代码
|
||||
- 🔲 `dependencies.md` - 明确的依赖关系图
|
||||
- 🔲 `test_scenarios.md` - 测试场景说明
|
||||
- 🔲 `integration_points.md` - 集成点说明
|
||||
|
||||
### 1.2 自包含原则
|
||||
- 每个Agent包应该是自包含的,包含所有必要信息
|
||||
- 使用相对路径引用共享文档
|
||||
- 将常用的代码片段直接包含在examples中
|
||||
|
||||
## 2. Agent间通信机制
|
||||
|
||||
### 2.1 接口契约管理
|
||||
```yaml
|
||||
# shared_contracts.yaml
|
||||
services:
|
||||
auth:
|
||||
provides:
|
||||
- get_current_user
|
||||
- require_admin
|
||||
- create_access_token
|
||||
requires: []
|
||||
|
||||
user:
|
||||
provides:
|
||||
- get_user_by_id
|
||||
- get_users_by_team
|
||||
requires:
|
||||
- auth.get_current_user
|
||||
```
|
||||
|
||||
### 2.2 Mock服务建议
|
||||
为每个Agent提供其他模块的Mock实现:
|
||||
```python
|
||||
# mocks/auth_mock.py
|
||||
async def get_current_user():
|
||||
return User(id=1, username="test_user", role="admin")
|
||||
```
|
||||
|
||||
## 3. 云端开发流程优化
|
||||
|
||||
### 3.1 Agent启动模板
|
||||
```markdown
|
||||
## 快速启动
|
||||
1. 我是 [Agent名称],负责 [模块名称]
|
||||
2. 我的工作目录是 [目录路径]
|
||||
3. 我依赖的模块有 [依赖列表]
|
||||
4. 我需要先检查 [前置条件]
|
||||
```
|
||||
|
||||
### 3.2 上下文同步机制
|
||||
- 创建共享的 `project_state.json` 记录各模块开发进度
|
||||
- 定期更新 `integration_status.md` 记录集成状态
|
||||
- 使用 `changelog.md` 记录重要变更
|
||||
|
||||
## 4. 质量保证策略
|
||||
|
||||
### 4.1 自动化检查脚本
|
||||
```python
|
||||
# scripts/check_agent_output.py
|
||||
def check_agent_code():
|
||||
"""检查Agent生成的代码质量"""
|
||||
- 检查import顺序
|
||||
- 验证类型注解
|
||||
- 确认异常处理
|
||||
- 验证日志记录
|
||||
```
|
||||
|
||||
### 4.2 集成测试协调
|
||||
```yaml
|
||||
# integration_test_plan.yaml
|
||||
test_order:
|
||||
1: auth # 独立模块,先测试
|
||||
2: user # 依赖auth
|
||||
3: [course, exam, training] # 可并行
|
||||
4: analytics # 依赖所有业务模块
|
||||
```
|
||||
|
||||
## 5. 协作沟通机制
|
||||
|
||||
### 5.1 状态报告模板
|
||||
```markdown
|
||||
## Agent-[Name] 状态报告
|
||||
- 完成度: 70%
|
||||
- 已完成: [功能列表]
|
||||
- 进行中: [功能列表]
|
||||
- 阻塞项: [问题列表]
|
||||
- 需要协调: [事项列表]
|
||||
```
|
||||
|
||||
### 5.2 问题升级机制
|
||||
1. Agent内部解决
|
||||
2. 查看其他Agent的实现
|
||||
3. 更新shared_contracts
|
||||
4. 人工介入协调
|
||||
|
||||
## 6. 性能和安全考虑
|
||||
|
||||
### 6.1 代码生成限制
|
||||
- 单个文件不超过500行
|
||||
- 复杂逻辑拆分为多个函数
|
||||
- 避免深层嵌套(最多3层)
|
||||
|
||||
### 6.2 安全检查点
|
||||
- 不硬编码敏感信息
|
||||
- 所有用户输入需验证
|
||||
- SQL查询使用参数化
|
||||
- API需要适当的权限检查
|
||||
|
||||
## 7. 持续改进建议
|
||||
|
||||
### 7.1 反馈循环
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent生成代码] --> B[自动化测试]
|
||||
B --> C[代码审查]
|
||||
C --> D[集成测试]
|
||||
D --> E[更新prompt]
|
||||
E --> A
|
||||
```
|
||||
|
||||
### 7.2 知识库建设
|
||||
- 收集常见错误和解决方案
|
||||
- 整理最佳实践代码片段
|
||||
- 更新Agent的示例代码
|
||||
- 优化prompt描述
|
||||
|
||||
## 8. 工具支持
|
||||
|
||||
### 8.1 辅助脚本
|
||||
```bash
|
||||
# 同步所有Agent的基础文件
|
||||
./scripts/sync_base_files.sh
|
||||
|
||||
# 检查Agent输出质量
|
||||
./scripts/validate_agent_output.sh
|
||||
|
||||
# 生成集成报告
|
||||
./scripts/generate_integration_report.sh
|
||||
```
|
||||
|
||||
### 8.2 监控面板
|
||||
创建简单的Web界面显示:
|
||||
- 各Agent的开发进度
|
||||
- 依赖关系图
|
||||
- 集成测试状态
|
||||
- 问题和阻塞项
|
||||
|
||||
## 9. 应急预案
|
||||
|
||||
### 9.1 Agent失效处理
|
||||
- 保留人工开发的备选方案
|
||||
- 关键模块优先人工review
|
||||
- 建立rollback机制
|
||||
|
||||
### 9.2 集成冲突解决
|
||||
- 明确的接口版本管理
|
||||
- 向后兼容原则
|
||||
- 灰度发布策略
|
||||
|
||||
## 10. 最终建议
|
||||
|
||||
1. **分阶段实施**:先让1-2个简单的Agent(如Auth)完成,验证流程
|
||||
2. **并行开发**:独立模块可以同时进行
|
||||
3. **频繁集成**:每日进行集成测试
|
||||
4. **持续优化**:根据实际效果调整prompt和流程
|
||||
5. **保持灵活**:准备人工介入的方案
|
||||
|
||||
通过这些实践,可以最大化利用AI Agent的能力,同时保证代码质量和项目进度。
|
||||
218
docs/规划/后端开发拆分策略/子agent/使用时的最佳实践.md
Normal file
218
docs/规划/后端开发拆分策略/子agent/使用时的最佳实践.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# 子Agent使用时的最佳实践
|
||||
|
||||
## 1. 推荐的引用方式
|
||||
|
||||
### 完整引用(最佳)
|
||||
```
|
||||
# 通用基础
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/project_structure.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
|
||||
# 架构规划(强烈推荐)
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
@考培练系统规划/后端开发拆分策略/开发规范文档.md
|
||||
|
||||
# Agent特定
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
@子agent/01-Agent-Auth/context.md
|
||||
@子agent/01-Agent-Auth/checklist.md
|
||||
|
||||
我是Agent-Auth,准备开始开发认证模块。
|
||||
我已经理解了项目的整体架构和协作机制。
|
||||
```
|
||||
|
||||
### 标准引用
|
||||
```
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
@子agent/01-Agent-Auth/context.md
|
||||
|
||||
按照Agent-Auth的角色开发认证模块。
|
||||
```
|
||||
|
||||
### 最小引用
|
||||
```
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
|
||||
开始开发Auth模块。
|
||||
```
|
||||
|
||||
## 2. Agent启动提示词模板
|
||||
|
||||
```markdown
|
||||
我是[Agent名称],我已经阅读了:
|
||||
1. 通用开发规范(base_prompt.md)
|
||||
2. 项目结构说明(project_structure.md)
|
||||
3. 我的角色定义(prompt.md)
|
||||
4. 项目上下文(context.md)
|
||||
|
||||
我理解我需要:
|
||||
- 遵循统一的代码规范
|
||||
- 使用项目的基础类和工具
|
||||
- 与其他模块保持接口一致
|
||||
- 编写测试和文档
|
||||
|
||||
项目根目录是:/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/
|
||||
|
||||
我现在开始按照checklist.md的步骤进行开发。
|
||||
```
|
||||
|
||||
## 3. 常见问题的预防性提醒
|
||||
|
||||
### 开始开发前
|
||||
```
|
||||
提醒:
|
||||
1. 所有import从app开始,不是从根目录
|
||||
2. 继承BaseModel和相应的Mixin
|
||||
3. 使用项目定义的异常类
|
||||
4. 遵循日志规范
|
||||
5. API响应使用ResponseModel包装
|
||||
```
|
||||
|
||||
### 创建新文件时
|
||||
```
|
||||
注意文件位置:
|
||||
- API路由放在 app/api/v1/
|
||||
- 模型放在 app/models/
|
||||
- Schema放在 app/schemas/
|
||||
- 服务放在 app/services/
|
||||
- 测试放在 tests/
|
||||
```
|
||||
|
||||
### 依赖其他模块时
|
||||
```
|
||||
检查依赖关系:
|
||||
- 从 app.api.deps 导入认证依赖
|
||||
- 不要循环依赖
|
||||
- 使用依赖注入而不是直接导入
|
||||
```
|
||||
|
||||
## 4. 分步开发策略
|
||||
|
||||
### 第一步:理解和规划
|
||||
```
|
||||
1. 仔细阅读所有文档
|
||||
2. 列出需要创建的文件
|
||||
3. 确认依赖关系
|
||||
4. 制定开发顺序
|
||||
```
|
||||
|
||||
### 第二步:创建基础结构
|
||||
```
|
||||
1. 先创建数据模型
|
||||
2. 定义Schema
|
||||
3. 创建空的Service类
|
||||
4. 创建路由框架
|
||||
```
|
||||
|
||||
### 第三步:实现核心功能
|
||||
```
|
||||
1. 实现一个最简单的功能
|
||||
2. 测试是否能正常运行
|
||||
3. 逐步添加其他功能
|
||||
4. 同步编写测试
|
||||
```
|
||||
|
||||
### 第四步:完善和优化
|
||||
```
|
||||
1. 添加错误处理
|
||||
2. 完善日志记录
|
||||
3. 优化性能
|
||||
4. 补充文档
|
||||
```
|
||||
|
||||
## 5. 协作开发技巧
|
||||
|
||||
### 模拟其他模块
|
||||
```python
|
||||
# 当依赖的模块还未完成时
|
||||
# mocks/auth.py
|
||||
async def get_current_user_mock():
|
||||
return User(id=1, username="test", role="admin")
|
||||
|
||||
# 在开发时临时使用
|
||||
from mocks.auth import get_current_user_mock as get_current_user
|
||||
```
|
||||
|
||||
### 定义接口契约
|
||||
```python
|
||||
# interfaces/auth_interface.py
|
||||
from typing import Protocol
|
||||
|
||||
class AuthServiceInterface(Protocol):
|
||||
async def get_current_user(self, token: str) -> User: ...
|
||||
async def verify_token(self, token: str) -> dict: ...
|
||||
```
|
||||
|
||||
### 集成测试桩
|
||||
```python
|
||||
# tests/stubs/external_service.py
|
||||
class DifyServiceStub:
|
||||
async def generate_exam_questions(self, **kwargs):
|
||||
return [{"question": "测试题目", "answer": "A"}]
|
||||
```
|
||||
|
||||
## 6. 输出质量检查
|
||||
|
||||
### 代码风格
|
||||
- [ ] 是否遵循了PEP 8
|
||||
- [ ] 导入是否按规范排序
|
||||
- [ ] 是否有类型注解
|
||||
- [ ] 文档字符串是否完整
|
||||
|
||||
### 功能完整性
|
||||
- [ ] 是否实现了所有要求的API
|
||||
- [ ] 错误处理是否完善
|
||||
- [ ] 日志记录是否充分
|
||||
- [ ] 是否有相应的测试
|
||||
|
||||
### 安全性
|
||||
- [ ] 是否有SQL注入风险
|
||||
- [ ] 是否验证了所有输入
|
||||
- [ ] 敏感信息是否加密
|
||||
- [ ] 权限检查是否到位
|
||||
|
||||
## 7. 调试和验证
|
||||
|
||||
### 快速验证API
|
||||
```python
|
||||
# 在main.py临时添加
|
||||
@app.get("/debug/routes")
|
||||
async def debug_routes():
|
||||
routes = []
|
||||
for route in app.routes:
|
||||
if hasattr(route, "methods"):
|
||||
routes.append({
|
||||
"path": route.path,
|
||||
"methods": list(route.methods),
|
||||
"name": route.name
|
||||
})
|
||||
return routes
|
||||
```
|
||||
|
||||
### 检查数据库连接
|
||||
```python
|
||||
# 临时健康检查
|
||||
@app.get("/debug/db")
|
||||
async def check_db(db: AsyncSession = Depends(get_db)):
|
||||
try:
|
||||
await db.execute("SELECT 1")
|
||||
return {"status": "connected"}
|
||||
except Exception as e:
|
||||
return {"status": "error", "message": str(e)}
|
||||
```
|
||||
|
||||
## 8. 持续改进
|
||||
|
||||
### 收集反馈
|
||||
- 记录Agent生成代码的问题
|
||||
- 改进prompt和示例
|
||||
- 更新checklist
|
||||
|
||||
### 知识共享
|
||||
- 将好的代码片段加入examples
|
||||
- 更新常见问题解答
|
||||
- 分享成功经验
|
||||
|
||||
通过遵循这些最佳实践,可以让Agent更高效、更准确地完成开发任务。
|
||||
130
docs/规划/后端开发拆分策略/子agent/创建完成说明.md
Normal file
130
docs/规划/后端开发拆分策略/子agent/创建完成说明.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# 子Agent工作包创建完成 ✅
|
||||
|
||||
## 创建时间
|
||||
2025年1月
|
||||
|
||||
## 已完成内容
|
||||
|
||||
### 1. 目录结构 ✅
|
||||
```
|
||||
子agent/
|
||||
├── README.md # 总体说明
|
||||
├── 快速使用指南.md # 使用指南
|
||||
├── 云端协作最佳实践.md # 协作建议
|
||||
├── 创建完成说明.md # 本文件
|
||||
├── 00-通用基础/ # 所有Agent共享
|
||||
│ ├── base_prompt.md # 通用规范
|
||||
│ └── project_structure.md # 项目结构
|
||||
├── 01-Agent-Auth/ # 认证授权
|
||||
│ ├── prompt.md # 完整提示词
|
||||
│ ├── context.md # 上下文信息
|
||||
│ ├── api_contract.yaml # API契约
|
||||
│ ├── checklist.md # 检查清单
|
||||
│ ├── dependencies.md # 依赖关系
|
||||
│ └── examples/ # 示例代码
|
||||
├── 02-Agent-User/ # 用户管理
|
||||
│ └── prompt.md
|
||||
├── 03-Agent-Course/ # 课程管理
|
||||
│ └── prompt.md
|
||||
├── 04-Agent-Exam/ # 考试模块
|
||||
│ └── prompt.md
|
||||
├── 05-Agent-Training/ # AI陪练
|
||||
│ └── prompt.md
|
||||
├── 06-Agent-Analytics/ # 数据分析
|
||||
│ └── prompt.md
|
||||
├── 07-Agent-Admin/ # 系统管理
|
||||
│ └── prompt.md
|
||||
├── 08-Agent-Coze/ # Coze集成
|
||||
│ └── prompt.md
|
||||
└── 09-Agent-Dify/ # Dify集成
|
||||
└── prompt.md
|
||||
```
|
||||
|
||||
### 2. 核心文件 ✅
|
||||
|
||||
#### 通用基础
|
||||
- `base_prompt.md` - 包含所有Agent必须遵循的开发规范
|
||||
- `project_structure.md` - 详细的项目目录结构说明
|
||||
|
||||
#### Agent-Auth(最完整的示例)
|
||||
- `prompt.md` - 详细的角色定义和开发任务
|
||||
- `context.md` - 项目上下文、数据库结构、环境变量
|
||||
- `api_contract.yaml` - OpenAPI格式的接口定义
|
||||
- `checklist.md` - 详细的开发检查清单
|
||||
- `dependencies.md` - 明确的依赖关系说明
|
||||
- `examples/` - 包含auth_service和auth_api的示例代码
|
||||
|
||||
#### 其他Agent
|
||||
- 每个都有基础的`prompt.md`文件
|
||||
- 包含角色定义、核心职责、主要功能、API端点等
|
||||
|
||||
### 3. 辅助文档 ✅
|
||||
- `快速使用指南.md` - 如何在Cursor中使用这些Agent
|
||||
- `云端协作最佳实践.md` - 提高协作效率的建议
|
||||
- `创建完成说明.md` - 记录完成情况
|
||||
|
||||
## 使用建议
|
||||
|
||||
### 1. 立即可用
|
||||
Agent-Auth的工作包最完整,可以立即开始使用:
|
||||
```bash
|
||||
# 将Agent-Auth文件夹上传到Cursor云端
|
||||
# 或在本地Cursor中引用这些文件
|
||||
```
|
||||
|
||||
### 2. 按需完善
|
||||
其他Agent已有基础prompt,可根据需要添加:
|
||||
- context.md
|
||||
- api_contract.yaml
|
||||
- checklist.md
|
||||
- examples/
|
||||
- dependencies.md
|
||||
|
||||
### 3. 开发顺序
|
||||
建议按以下顺序开发:
|
||||
1. Agent-Auth(基础)
|
||||
2. Agent-User(依赖Auth)
|
||||
3. Agent-Coze & Agent-Dify(AI服务)
|
||||
4. 其他业务模块(并行开发)
|
||||
5. Agent-Analytics(依赖所有模块)
|
||||
|
||||
## 下一步行动
|
||||
|
||||
1. **测试Agent-Auth**
|
||||
- 使用完整的Auth工作包测试效果
|
||||
- 根据结果优化prompt和示例
|
||||
|
||||
2. **完善其他Agent**
|
||||
- 基于Auth的模板完善其他Agent文件
|
||||
- 特别是context.md和examples
|
||||
|
||||
3. **创建共享资源**
|
||||
- Mock服务集合
|
||||
- 集成测试套件
|
||||
- 状态同步机制
|
||||
|
||||
4. **监控和优化**
|
||||
- 跟踪各Agent的输出质量
|
||||
- 收集常见问题
|
||||
- 持续优化prompt
|
||||
|
||||
## 特色亮点
|
||||
|
||||
✨ **模块化设计** - 每个Agent独立且职责明确
|
||||
✨ **完整示例** - Agent-Auth提供了完整的参考
|
||||
✨ **协作机制** - 明确的依赖关系和接口定义
|
||||
✨ **质量保证** - 详细的检查清单和测试要求
|
||||
✨ **灵活扩展** - 易于添加新的Agent或功能
|
||||
|
||||
## 重要提醒
|
||||
|
||||
⚠️ 这些Agent工作包是基于项目需求设计的指导文档
|
||||
⚠️ 实际开发中可能需要根据情况调整
|
||||
⚠️ 保持Agent之间的接口稳定性很重要
|
||||
⚠️ 定期同步和集成测试是成功的关键
|
||||
|
||||
---
|
||||
|
||||
**状态**: ✅ 已完成子Agent工作包的创建
|
||||
**位置**: `/Users/nongjun/Desktop/Ai公司/本地开发与测试/考培练系统规划/后端开发拆分策略/子agent/`
|
||||
**可用性**: 立即可用于Cursor云端或本地开发
|
||||
207
docs/规划/后端开发拆分策略/子agent/快速使用指南.md
Normal file
207
docs/规划/后端开发拆分策略/子agent/快速使用指南.md
Normal file
@@ -0,0 +1,207 @@
|
||||
# 子Agent快速使用指南
|
||||
|
||||
## 1. 在Cursor中使用Agent
|
||||
|
||||
### 方式一:作为系统提示词
|
||||
1. 打开Cursor的设置
|
||||
2. 找到"AI"或"Assistant"设置
|
||||
3. 将Agent的`prompt.md`内容复制到系统提示词
|
||||
4. 添加相关的context文件作为参考
|
||||
|
||||
### 方式二:在对话中引用(推荐)
|
||||
|
||||
#### 完整引用(包含架构文档 - 最推荐)
|
||||
```
|
||||
# 基础规范
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/00-通用基础/essential_docs.md
|
||||
|
||||
# 架构设计(重要)
|
||||
@考培练系统规划/后端开发拆分策略/协作机制设计.md
|
||||
@考培练系统规划/后端开发拆分策略/模块分工指南.md
|
||||
|
||||
# Agent特定文档
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
@子agent/01-Agent-Auth/context.md
|
||||
|
||||
请按照Agent-Auth的角色开始开发认证模块
|
||||
```
|
||||
|
||||
#### 标准引用(一般情况)
|
||||
```
|
||||
@子agent/00-通用基础/base_prompt.md
|
||||
@子agent/01-Agent-Auth/prompt.md
|
||||
@子agent/01-Agent-Auth/context.md
|
||||
|
||||
请按照Agent-Auth的角色开始开发认证模块
|
||||
```
|
||||
|
||||
**注意**:
|
||||
- 完整引用能让Agent更好地理解项目架构和协作机制
|
||||
- 每个Agent的context.md现在都包含了对重要规划文档的引用
|
||||
- 但在对话中明确包含这些文档可以确保Agent完全理解所有设计决策
|
||||
|
||||
### 方式三:创建专门的工作空间
|
||||
1. 为每个Agent创建独立的Cursor工作空间
|
||||
2. 将Agent文件夹的内容复制进去
|
||||
3. 设置.cursorrules文件指向prompt.md
|
||||
|
||||
## 2. 开发顺序建议
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[1. Agent-Auth<br/>认证授权] --> B[2. Agent-User<br/>用户管理]
|
||||
A --> C[3. Agent-Coze<br/>Coze集成]
|
||||
A --> D[4. Agent-Dify<br/>Dify集成]
|
||||
B --> E[5. Agent-Course<br/>课程管理]
|
||||
C --> F[6. Agent-Training<br/>AI陪练]
|
||||
D --> G[7. Agent-Exam<br/>考试模块]
|
||||
E --> H[8. Agent-Analytics<br/>数据分析]
|
||||
F --> H
|
||||
G --> H
|
||||
B --> I[9. Agent-Admin<br/>系统管理]
|
||||
```
|
||||
|
||||
## 3. 快速启动检查清单
|
||||
|
||||
### 启动Agent前
|
||||
- [ ] 确认项目脚手架已创建
|
||||
- [ ] 数据库已配置并运行
|
||||
- [ ] 已创建feature分支
|
||||
- [ ] 已阅读通用基础规范
|
||||
|
||||
### 启动Agent时
|
||||
```markdown
|
||||
我是[Agent名称],我需要:
|
||||
1. 查看我的prompt.md了解职责
|
||||
2. 查看context.md了解项目结构
|
||||
3. 查看api_contract.yaml了解接口规范
|
||||
4. 查看examples/目录的示例代码
|
||||
5. 按照checklist.md开始开发
|
||||
```
|
||||
|
||||
### Agent工作时
|
||||
- 先创建数据模型
|
||||
- 再创建Schema
|
||||
- 然后实现Service
|
||||
- 最后完成API路由
|
||||
- 同步编写测试
|
||||
|
||||
## 4. 常见问题处理
|
||||
|
||||
### Q: Agent不了解项目结构
|
||||
A: 提供以下上下文:
|
||||
```
|
||||
项目根目录: /Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/
|
||||
查看: @子agent/00-通用基础/project_structure.md
|
||||
```
|
||||
|
||||
### Q: Agent不遵循代码规范
|
||||
A: 提醒查看:
|
||||
```
|
||||
请严格遵循: @子agent/00-通用基础/base_prompt.md
|
||||
特别注意代码规范部分
|
||||
```
|
||||
|
||||
### Q: Agent创建了错误的导入路径
|
||||
A: 明确指出:
|
||||
```
|
||||
所有导入都应该从app开始,例如:
|
||||
from app.core.deps import get_db
|
||||
from app.models.user import User
|
||||
```
|
||||
|
||||
### Q: Agent忘记依赖关系
|
||||
A: 查看依赖文档:
|
||||
```
|
||||
查看: @子agent/[Agent编号]/dependencies.md
|
||||
确保正确导入和使用依赖模块的功能
|
||||
```
|
||||
|
||||
## 5. 集成测试节点
|
||||
|
||||
### 第一个集成点:Auth + User
|
||||
```bash
|
||||
# 测试认证功能
|
||||
pytest tests/integration/test_auth_user.py
|
||||
|
||||
# 验证要点:
|
||||
- 用户注册后能登录
|
||||
- Token能正确识别用户
|
||||
- 权限检查正常工作
|
||||
```
|
||||
|
||||
### 第二个集成点:Course + Exam + Training
|
||||
```bash
|
||||
# 测试业务功能
|
||||
pytest tests/integration/test_business_modules.py
|
||||
|
||||
# 验证要点:
|
||||
- 课程创建后能生成考题
|
||||
- 陪练场景能关联课程
|
||||
- 数据正确流转
|
||||
```
|
||||
|
||||
### 最终集成:Analytics
|
||||
```bash
|
||||
# 测试数据分析
|
||||
pytest tests/integration/test_analytics.py
|
||||
|
||||
# 验证要点:
|
||||
- 能聚合各模块数据
|
||||
- 报表生成正确
|
||||
- 性能符合要求
|
||||
```
|
||||
|
||||
## 6. 提交规范
|
||||
|
||||
### 每个Agent完成后
|
||||
1. 运行所有代码检查
|
||||
2. 确保测试通过
|
||||
3. 更新集成状态
|
||||
4. 提交格式:
|
||||
```
|
||||
feat(auth): 完成认证授权模块
|
||||
|
||||
- 实现用户登录、注册、登出功能
|
||||
- 添加JWT Token管理
|
||||
- 实现权限检查中间件
|
||||
- 完成所有单元测试
|
||||
- 测试覆盖率: 85%
|
||||
|
||||
Closes #[issue-number]
|
||||
```
|
||||
|
||||
## 7. 调试技巧
|
||||
|
||||
### 查看Agent生成的代码
|
||||
```python
|
||||
# 在生成的代码中添加
|
||||
print("=== Agent-Auth Generated ===")
|
||||
# 你的代码
|
||||
print("=== End of Generation ===")
|
||||
```
|
||||
|
||||
### 验证API是否正确注册
|
||||
```python
|
||||
# 在main.py中添加
|
||||
for route in app.routes:
|
||||
print(f"{route.methods} {route.path}")
|
||||
```
|
||||
|
||||
### 检查依赖注入
|
||||
```python
|
||||
# 测试依赖是否工作
|
||||
@router.get("/test-auth")
|
||||
async def test_auth(user: User = Depends(get_current_user)):
|
||||
return {"user_id": user.id, "username": user.username}
|
||||
```
|
||||
|
||||
## 8. 优化建议
|
||||
|
||||
1. **让Agent分步工作**:不要一次要求太多,分步骤进行
|
||||
2. **提供明确的示例**:使用examples目录的代码作为参考
|
||||
3. **及时纠正错误**:发现问题立即指出并提供正确示例
|
||||
4. **保存好的输出**:将优秀的代码保存到examples中供后续参考
|
||||
|
||||
祝开发顺利! 🚀
|
||||
104
docs/规划/后端开发拆分策略/子agent集成todos清单.md
Normal file
104
docs/规划/后端开发拆分策略/子agent集成todos清单.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# 子Agent开发完成后的本地集成Todos清单
|
||||
|
||||
## 使用说明
|
||||
|
||||
完成子agent后端开发并手动Apply Changes Locally后,将此清单直接粘贴给子agent执行。
|
||||
**重点:前端已开发完成,需要验证后端API与前端页面的完整对接。**
|
||||
|
||||
集成经验(必读):/Users/nongjun/Desktop/Ai公司/本地开发与测试/考培练系统规划/后端开发拆分策略/子agent/00-通用基础/integration_experience.md
|
||||
|
||||
---
|
||||
|
||||
## 📋 集成Todos清单
|
||||
|
||||
### 🔧 配置检查与修复
|
||||
|
||||
- [ ] 检查并创建.env文件(如不存在则从.env.example复制)
|
||||
- [ ] 确认数据库配置:`DATABASE_URL=mysql+aiomysql://root:root@localhost:3306/kaopeilian?charset=utf8mb4`
|
||||
- [ ] 安装/更新Python依赖:`pip install -r requirements/dev.txt`
|
||||
- [ ] 检查是否有新模型文件在 `app/models/`目录
|
||||
|
||||
### 🗄️ 数据库迁移(注意:数据库已按设计对齐,无需重复初始化与插入内置测试数据)
|
||||
|
||||
- [ ] 如有新模型,生成迁移:`alembic revision --autogenerate -m "add new models"`
|
||||
- [ ] 查看迁移文件:`ls migrations/versions/`
|
||||
- [ ] 应用迁移:`alembic upgrade head`
|
||||
- [ ] 校验视图存在:`SELECT * FROM v_user_course_progress LIMIT 1;`
|
||||
|
||||
> 说明:
|
||||
> - 已存在并对齐的基础表(users/teams/user_teams/courses/.../training_*)不应被重复创建或清空。
|
||||
> - 如需新增表或字段,请仅通过 Alembic 迁移进行增量更新。
|
||||
|
||||
### 🚀 服务启动
|
||||
|
||||
- [ ] 在 `kaopeilian-backend/`目录执行以下命令
|
||||
- [ ] 启动MySQL和Redis:`docker-compose -f docker-compose.dev.yml up -d mysql redis`
|
||||
- [ ] 验证服务状态:`docker-compose -f docker-compose.dev.yml ps`
|
||||
- [ ] 启动后端服务:`uvicorn app.main:app --reload --host 0.0.0.0 --port 8000`
|
||||
- [ ] 可选:使用Makefile快捷命令:`make migrate`、`make run`
|
||||
|
||||
### ✅ 后端API验证
|
||||
|
||||
- [ ] 健康检查:`curl http://localhost:8000/health`
|
||||
- [ ] 访问API文档:`http://localhost:8000/docs`
|
||||
- [ ] 测试新开发的API端点(依据OpenAPI文档与 `app/contracts`中的模块契约)
|
||||
- [ ] 验证API响应格式:确保返回的JSON结构符合前端预期
|
||||
- [ ] 测试认证授权:确认JWT token验证正常工作
|
||||
- [ ] 测试错误处理:验证4xx/5xx错误返回格式正确
|
||||
|
||||
### 🌐 前后端对接验证(重要:前端已开发完成)
|
||||
|
||||
- [ ] 确认CORS配置:检查 `app/config/settings.py`中的 `CORS_ORIGINS`包含 `http://localhost:3001`
|
||||
- [ ] 启动前端服务:`cd ../kaopeilian-frontend && npm run dev`
|
||||
- [ ] 访问前端页面:`http://localhost:3001`
|
||||
- [ ] 确认前端 `src/api/config.ts`的 `baseURL`为 `http://localhost:8000`
|
||||
- [ ] 验证API接口对接:在前端页面测试新开发的后端功能
|
||||
- [ ] 检查浏览器网络面板:确认API请求/响应格式正确
|
||||
- [ ] 检查浏览器控制台:无CORS错误、无JS错误
|
||||
- [ ] 测试前端页面功能:登录、数据加载、操作反馈等
|
||||
- [ ] 验证数据流:前端操作→后端API→数据库→返回前端显示
|
||||
|
||||
### 🧪 测试验证
|
||||
|
||||
- [ ] 运行单元测试:`pytest tests/ -v`
|
||||
- [ ] 检查测试覆盖率:`pytest --cov=app --cov-report=html tests/`
|
||||
- [ ] 代码格式化:`black app/ tests/`
|
||||
- [ ] 代码质量检查:`flake8 app/ tests/`
|
||||
|
||||
### 📝 文档更新
|
||||
|
||||
- [ ] 检查是否需要更新 `README.md`
|
||||
- [ ] 检查是否需要更新 `数据库架构.md`
|
||||
- [ ] 如有架构调整、配置变更、运行逻辑变更,必须更新相关文档
|
||||
|
||||
### 💾 代码提交
|
||||
|
||||
- [ ] 查看变更:`git status && git diff`
|
||||
- [ ] 添加变更:`git add .`
|
||||
- [ ] 提交变更:`git commit -m "feat(module): 描述变更内容"`
|
||||
- [ ] 推送代码:`git push origin main`
|
||||
|
||||
### ⚠️ 问题排查(如遇到问题时执行)
|
||||
|
||||
- [ ] 数据库连接失败:检查 `docker-compose -f docker-compose.dev.yml logs mysql`
|
||||
- [ ] CORS错误:检查 `app/config/settings.py`中的 `CORS_ORIGINS`
|
||||
- [ ] 前端API调用失败:检查浏览器网络面板,确认请求URL和方法正确
|
||||
- [ ] 前端页面显示异常:检查API返回的数据格式是否符合前端预期
|
||||
- [ ] 认证问题:确认JWT token格式和过期时间设置正确
|
||||
- [ ] 依赖冲突:删除venv重新创建虚拟环境
|
||||
- [ ] 端口占用:`lsof -i :8000` 查看端口占用情况
|
||||
|
||||
---
|
||||
|
||||
## 🎯 最终验收标准
|
||||
|
||||
- [ ] 所有新增API端点正常响应
|
||||
- [ ] 数据库迁移成功应用(无重复初始化)
|
||||
- [ ] 单元测试通过率≥80%
|
||||
- [ ] 前后端对接完全正常
|
||||
- [ ] 文档已更新(如有架构/配置变更)
|
||||
- [ ] 代码已提交到版本控制
|
||||
|
||||
---
|
||||
|
||||
**注意:此清单适用于考培练系统(Python+Vue3+MySQL+FastAPI)的本地开发测试环境**
|
||||
380
docs/规划/后端开发拆分策略/开发规范文档.md
Normal file
380
docs/规划/后端开发拆分策略/开发规范文档.md
Normal file
@@ -0,0 +1,380 @@
|
||||
# 考培练系统后端开发规范
|
||||
|
||||
## 1. 代码规范
|
||||
|
||||
### 1.1 Python代码规范
|
||||
- **格式化工具**:使用 Black 进行代码格式化,配置行长度为 88
|
||||
- **导入排序**:使用 isort 进行导入排序
|
||||
- **类型检查**:使用 mypy 进行静态类型检查
|
||||
- **代码检查**:使用 flake8 进行代码质量检查
|
||||
|
||||
### 1.2 命名规范
|
||||
```python
|
||||
# 文件名:使用小写字母和下划线
|
||||
user_service.py
|
||||
|
||||
# 类名:使用大驼峰命名法
|
||||
class UserService:
|
||||
pass
|
||||
|
||||
# 函数和变量:使用小写字母和下划线
|
||||
def get_user_by_id(user_id: int) -> User:
|
||||
pass
|
||||
|
||||
# 常量:使用大写字母和下划线
|
||||
MAX_RETRY_COUNT = 3
|
||||
|
||||
# 私有成员:使用单下划线前缀
|
||||
def _validate_input(data: dict) -> bool:
|
||||
pass
|
||||
```
|
||||
|
||||
### 1.3 文档字符串规范
|
||||
```python
|
||||
def create_user(
|
||||
username: str,
|
||||
email: str,
|
||||
password: str,
|
||||
role: UserRole = UserRole.TRAINEE
|
||||
) -> User:
|
||||
"""
|
||||
创建新用户
|
||||
|
||||
Args:
|
||||
username: 用户名,长度3-20个字符
|
||||
email: 用户邮箱,必须是有效的邮箱格式
|
||||
password: 密码,最少8个字符
|
||||
role: 用户角色,默认为学员
|
||||
|
||||
Returns:
|
||||
User: 创建成功的用户对象
|
||||
|
||||
Raises:
|
||||
ValidationError: 输入参数验证失败
|
||||
DuplicateError: 用户名或邮箱已存在
|
||||
"""
|
||||
pass
|
||||
```
|
||||
|
||||
## 2. API开发规范
|
||||
|
||||
### 2.1 RESTful API设计原则
|
||||
- 使用名词而非动词
|
||||
- 使用复数形式
|
||||
- 使用标准HTTP方法
|
||||
- 合理使用HTTP状态码
|
||||
|
||||
```python
|
||||
# 好的例子
|
||||
GET /api/v1/users # 获取用户列表
|
||||
GET /api/v1/users/{id} # 获取单个用户
|
||||
POST /api/v1/users # 创建用户
|
||||
PUT /api/v1/users/{id} # 更新用户
|
||||
DELETE /api/v1/users/{id} # 删除用户
|
||||
|
||||
# 错误的例子
|
||||
GET /api/v1/getUsers # 不要使用动词
|
||||
POST /api/v1/user/create # 不要在URL中包含动作
|
||||
```
|
||||
|
||||
### 2.2 统一响应格式
|
||||
```python
|
||||
from typing import Optional, Any
|
||||
from pydantic import BaseModel
|
||||
|
||||
class ResponseModel(BaseModel):
|
||||
"""统一API响应模型"""
|
||||
code: int = 200
|
||||
message: str = "success"
|
||||
data: Optional[Any] = None
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""错误响应模型"""
|
||||
code: int
|
||||
message: str
|
||||
details: Optional[str] = None
|
||||
trace_id: Optional[str] = None
|
||||
|
||||
# 成功响应示例
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"id": 1,
|
||||
"username": "张三",
|
||||
"email": "zhangsan@example.com"
|
||||
}
|
||||
}
|
||||
|
||||
# 错误响应示例
|
||||
{
|
||||
"code": 400,
|
||||
"message": "参数验证失败",
|
||||
"details": "用户名长度必须在3-20个字符之间",
|
||||
"trace_id": "abc123def456"
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 API版本控制
|
||||
- 使用URL路径进行版本控制:`/api/v1/`, `/api/v2/`
|
||||
- 保持向后兼容,避免破坏性更改
|
||||
- 废弃的API需要提前通知并设置过渡期
|
||||
|
||||
## 3. 数据库规范
|
||||
|
||||
### 3.1 表命名规范
|
||||
- 使用复数形式:`users`, `courses`, `exams`
|
||||
- 关联表使用下划线连接:`user_courses`, `exam_questions`
|
||||
- 避免使用MySQL保留字
|
||||
|
||||
### 3.2 字段命名规范
|
||||
- 使用蛇形命名法:`user_name`, `created_at`
|
||||
- 主键统一使用 `id`
|
||||
- 外键使用 `表名_id` 格式:`user_id`, `course_id`
|
||||
|
||||
### 3.3 必需字段
|
||||
每个表必须包含以下字段:
|
||||
```sql
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT -- 主键
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- 创建时间
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP -- 更新时间
|
||||
created_by BIGINT -- 创建人ID(可选)
|
||||
updated_by BIGINT -- 更新人ID(可选)
|
||||
is_deleted BOOLEAN DEFAULT FALSE -- 软删除标记(如需要)
|
||||
```
|
||||
|
||||
### 3.4 索引规范
|
||||
- 为外键字段创建索引
|
||||
- 为经常查询的字段创建索引
|
||||
- 避免创建过多索引影响写入性能
|
||||
- 索引命名:`idx_表名_字段名`
|
||||
|
||||
## 4. 异常处理规范
|
||||
|
||||
### 4.1 自定义异常类
|
||||
```python
|
||||
# app/core/exceptions.py
|
||||
class BaseAPIException(Exception):
|
||||
"""API异常基类"""
|
||||
def __init__(
|
||||
self,
|
||||
code: int,
|
||||
message: str,
|
||||
details: str = None
|
||||
):
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.details = details
|
||||
super().__init__(message)
|
||||
|
||||
class ValidationError(BaseAPIException):
|
||||
"""参数验证异常"""
|
||||
def __init__(self, message: str, details: str = None):
|
||||
super().__init__(400, message, details)
|
||||
|
||||
class NotFoundError(BaseAPIException):
|
||||
"""资源不存在异常"""
|
||||
def __init__(self, resource: str):
|
||||
super().__init__(404, f"{resource}不存在")
|
||||
|
||||
class PermissionError(BaseAPIException):
|
||||
"""权限不足异常"""
|
||||
def __init__(self, message: str = "权限不足"):
|
||||
super().__init__(403, message)
|
||||
```
|
||||
|
||||
### 4.2 全局异常处理
|
||||
```python
|
||||
# app/core/middleware.py
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
"""全局异常处理器"""
|
||||
if isinstance(exc, BaseAPIException):
|
||||
return JSONResponse(
|
||||
status_code=exc.code,
|
||||
content={
|
||||
"code": exc.code,
|
||||
"message": exc.message,
|
||||
"details": exc.details,
|
||||
"trace_id": request.state.trace_id
|
||||
}
|
||||
)
|
||||
|
||||
# 记录未预期的异常
|
||||
logger.error(f"未处理的异常: {exc}", exc_info=True)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"code": 500,
|
||||
"message": "服务器内部错误",
|
||||
"trace_id": request.state.trace_id
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## 5. 日志规范
|
||||
|
||||
### 5.1 日志级别使用
|
||||
- **DEBUG**: 调试信息,仅在开发环境使用
|
||||
- **INFO**: 一般信息,如API请求、重要业务操作
|
||||
- **WARNING**: 警告信息,如已废弃的API调用
|
||||
- **ERROR**: 错误信息,需要关注但不影响系统运行
|
||||
- **CRITICAL**: 严重错误,可能导致系统无法正常运行
|
||||
|
||||
### 5.2 结构化日志
|
||||
```python
|
||||
import structlog
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
# 使用结构化日志
|
||||
logger.info(
|
||||
"用户登录成功",
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
ip_address=request.client.host,
|
||||
user_agent=request.headers.get("user-agent")
|
||||
)
|
||||
|
||||
# 记录错误信息
|
||||
logger.error(
|
||||
"数据库连接失败",
|
||||
error=str(e),
|
||||
database_url=settings.DATABASE_URL,
|
||||
retry_count=retry_count,
|
||||
exc_info=True # 包含完整堆栈信息
|
||||
)
|
||||
```
|
||||
|
||||
### 5.3 日志格式配置
|
||||
```python
|
||||
# app/core/logger.py
|
||||
import structlog
|
||||
|
||||
def configure_logging():
|
||||
structlog.configure(
|
||||
processors=[
|
||||
structlog.stdlib.filter_by_level,
|
||||
structlog.stdlib.add_logger_name,
|
||||
structlog.stdlib.add_log_level,
|
||||
structlog.stdlib.PositionalArgumentsFormatter(),
|
||||
structlog.processors.TimeStamper(fmt="iso"),
|
||||
structlog.processors.StackInfoRenderer(),
|
||||
structlog.processors.format_exc_info,
|
||||
structlog.processors.UnicodeDecoder(),
|
||||
structlog.processors.JSONRenderer()
|
||||
],
|
||||
context_class=dict,
|
||||
logger_factory=structlog.stdlib.LoggerFactory(),
|
||||
cache_logger_on_first_use=True,
|
||||
)
|
||||
```
|
||||
|
||||
## 6. 测试规范
|
||||
|
||||
### 6.1 测试文件组织
|
||||
```
|
||||
tests/
|
||||
├── unit/ # 单元测试
|
||||
│ ├── test_services/
|
||||
│ └── test_utils/
|
||||
├── integration/ # 集成测试
|
||||
│ ├── test_api/
|
||||
│ └── test_database/
|
||||
└── e2e/ # 端到端测试
|
||||
└── test_workflows/
|
||||
```
|
||||
|
||||
### 6.2 测试命名规范
|
||||
```python
|
||||
# 测试文件名:test_模块名.py
|
||||
test_user_service.py
|
||||
|
||||
# 测试类名:Test + 被测试类名
|
||||
class TestUserService:
|
||||
pass
|
||||
|
||||
# 测试方法名:test_应该_做什么_当什么条件
|
||||
def test_should_create_user_when_valid_data(self):
|
||||
pass
|
||||
|
||||
def test_should_raise_error_when_duplicate_username(self):
|
||||
pass
|
||||
```
|
||||
|
||||
### 6.3 测试覆盖率要求
|
||||
- 核心业务逻辑:≥ 90%
|
||||
- API接口:≥ 80%
|
||||
- 工具函数:≥ 70%
|
||||
- 总体覆盖率:≥ 80%
|
||||
|
||||
## 7. Git提交规范
|
||||
|
||||
### 7.1 提交信息格式
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
|
||||
<body>
|
||||
|
||||
<footer>
|
||||
```
|
||||
|
||||
### 7.2 Type类型
|
||||
- **feat**: 新功能
|
||||
- **fix**: 修复bug
|
||||
- **docs**: 文档更新
|
||||
- **style**: 代码格式调整
|
||||
- **refactor**: 代码重构
|
||||
- **test**: 测试相关
|
||||
- **chore**: 构建过程或辅助工具的变动
|
||||
|
||||
### 7.3 示例
|
||||
```
|
||||
feat(user): 添加用户批量导入功能
|
||||
|
||||
- 支持Excel文件导入
|
||||
- 支持CSV文件导入
|
||||
- 添加导入进度显示
|
||||
- 添加错误信息导出
|
||||
|
||||
Closes #123
|
||||
```
|
||||
|
||||
## 8. 代码审查清单
|
||||
|
||||
提交代码前,请确保:
|
||||
|
||||
### 基础检查
|
||||
- [ ] 代码通过 Black 格式化
|
||||
- [ ] 代码通过 isort 导入排序
|
||||
- [ ] 代码通过 mypy 类型检查
|
||||
- [ ] 代码通过 flake8 质量检查
|
||||
|
||||
### 功能检查
|
||||
- [ ] 所有函数都有完整的文档字符串
|
||||
- [ ] 所有函数都有类型注解
|
||||
- [ ] API响应格式符合统一标准
|
||||
- [ ] 错误处理使用统一的异常类
|
||||
|
||||
### 测试检查
|
||||
- [ ] 编写了相应的单元测试
|
||||
- [ ] 测试覆盖率符合要求
|
||||
- [ ] 所有测试通过
|
||||
|
||||
### 安全检查
|
||||
- [ ] 没有硬编码的密钥或密码
|
||||
- [ ] SQL查询使用参数化查询
|
||||
- [ ] 敏感操作有权限检查
|
||||
|
||||
### 性能检查
|
||||
- [ ] 数据库查询使用了适当的索引
|
||||
- [ ] 避免了N+1查询问题
|
||||
- [ ] 大量数据处理使用了分页或流式处理
|
||||
|
||||
### 日志检查
|
||||
- [ ] 关键操作有日志记录
|
||||
- [ ] 错误信息包含完整的上下文
|
||||
- [ ] 日志级别使用恰当
|
||||
|
||||
521
docs/规划/后端开发拆分策略/快速开始指南.md
Normal file
521
docs/规划/后端开发拆分策略/快速开始指南.md
Normal file
@@ -0,0 +1,521 @@
|
||||
# 考培练系统后端快速开始指南
|
||||
|
||||
## 1. 环境准备
|
||||
|
||||
### 1.1 系统要求
|
||||
- Python 3.8+
|
||||
- MySQL 8.0+
|
||||
- Redis 6.0+
|
||||
- Node.js 16+ (用于前端开发)
|
||||
- Git
|
||||
|
||||
### 1.2 推荐开发工具
|
||||
- IDE: PyCharm / VSCode with Python插件
|
||||
- API测试: Postman / Insomnia
|
||||
- 数据库管理: DBeaver / MySQL Workbench
|
||||
- Redis管理: RedisInsight
|
||||
|
||||
## 2. 项目初始化
|
||||
|
||||
### 2.1 克隆项目
|
||||
```bash
|
||||
# 克隆项目到本地
|
||||
git clone <repository-url> kaopeilian-backend
|
||||
cd kaopeilian-backend
|
||||
```
|
||||
|
||||
### 2.2 创建Python虚拟环境
|
||||
```bash
|
||||
# 创建虚拟环境
|
||||
python3 -m venv venv
|
||||
|
||||
# 激活虚拟环境
|
||||
# Linux/Mac:
|
||||
source venv/bin/activate
|
||||
# Windows:
|
||||
venv\Scripts\activate
|
||||
|
||||
# 升级pip
|
||||
pip install --upgrade pip
|
||||
```
|
||||
|
||||
### 2.3 安装依赖
|
||||
```bash
|
||||
# 安装所有依赖
|
||||
pip install -r requirements/dev.txt
|
||||
|
||||
# 或者分别安装
|
||||
pip install -r requirements/base.txt # 基础依赖
|
||||
pip install -r requirements/dev.txt # 开发依赖
|
||||
```
|
||||
|
||||
### 2.4 环境配置
|
||||
```bash
|
||||
# 复制环境变量示例文件
|
||||
cp .env.example .env
|
||||
|
||||
# 编辑.env文件,配置以下关键变量:
|
||||
```
|
||||
|
||||
编辑 `.env` 文件:
|
||||
```env
|
||||
# 基础配置
|
||||
PROJECT_NAME="考培练系统"
|
||||
VERSION="1.0.0"
|
||||
DEBUG=true
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
# 安全配置
|
||||
SECRET_KEY="your-secret-key-here-must-be-at-least-32-chars"
|
||||
|
||||
# 数据库配置
|
||||
DATABASE_URL="mysql+aiomysql://root:password@localhost:3306/kaopeilian"
|
||||
|
||||
# Redis配置
|
||||
REDIS_URL="redis://localhost:6379/0"
|
||||
|
||||
# Coze平台配置
|
||||
COZE_API_BASE="https://api.coze.cn"
|
||||
COZE_WORKSPACE_ID="your-workspace-id"
|
||||
COZE_API_TOKEN="pat_your_token_here"
|
||||
COZE_TRAINING_BOT_ID="your-training-bot-id"
|
||||
COZE_CHAT_BOT_ID="your-chat-bot-id"
|
||||
|
||||
# Dify平台配置
|
||||
DIFY_API_BASE="https://api.dify.ai/v1"
|
||||
DIFY_API_KEY="app-your-api-key-here"
|
||||
DIFY_EXAM_WORKFLOW_ID="workflow_exam_id"
|
||||
DIFY_ASSESSMENT_WORKFLOW_ID="workflow_assessment_id"
|
||||
DIFY_RECOMMEND_WORKFLOW_ID="workflow_recommend_id"
|
||||
|
||||
# CORS配置
|
||||
CORS_ORIGINS=["http://localhost:5173", "http://localhost:3000"]
|
||||
```
|
||||
|
||||
## 3. 数据库初始化
|
||||
|
||||
### 3.1 创建数据库
|
||||
```sql
|
||||
-- 连接到MySQL
|
||||
mysql -u root -p
|
||||
|
||||
-- 创建数据库
|
||||
CREATE DATABASE kaopeilian CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- 创建专用用户(可选)
|
||||
CREATE USER 'kaopeilian'@'localhost' IDENTIFIED BY 'your_password';
|
||||
GRANT ALL PRIVILEGES ON kaopeilian.* TO 'kaopeilian'@'localhost';
|
||||
FLUSH PRIVILEGES;
|
||||
```
|
||||
|
||||
### 3.2 初始化Alembic(数据库迁移)
|
||||
```bash
|
||||
# 如果还没有初始化过
|
||||
alembic init migrations
|
||||
|
||||
# 编辑 alembic.ini,设置数据库URL
|
||||
# sqlalchemy.url = mysql+aiomysql://root:password@localhost:3306/kaopeilian
|
||||
```
|
||||
|
||||
### 3.3 创建初始迁移
|
||||
```bash
|
||||
# 生成初始迁移文件
|
||||
alembic revision --autogenerate -m "initial tables"
|
||||
|
||||
# 查看生成的迁移文件
|
||||
ls migrations/versions/
|
||||
|
||||
# 应用迁移
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
### 3.4 创建种子数据(可选)
|
||||
```bash
|
||||
# 运行种子数据脚本
|
||||
python scripts/seed_data.py
|
||||
```
|
||||
|
||||
## 4. 启动服务
|
||||
|
||||
### 4.1 启动依赖服务
|
||||
|
||||
使用Docker Compose启动MySQL和Redis:
|
||||
```bash
|
||||
# 启动依赖服务
|
||||
docker-compose up -d mysql redis
|
||||
|
||||
# 查看服务状态
|
||||
docker-compose ps
|
||||
|
||||
# 查看日志
|
||||
docker-compose logs -f mysql
|
||||
docker-compose logs -f redis
|
||||
```
|
||||
|
||||
或者手动启动本地服务:
|
||||
```bash
|
||||
# 启动MySQL
|
||||
sudo systemctl start mysql
|
||||
# 或
|
||||
brew services start mysql # macOS
|
||||
|
||||
# 启动Redis
|
||||
sudo systemctl start redis
|
||||
# 或
|
||||
brew services start redis # macOS
|
||||
```
|
||||
|
||||
### 4.2 启动开发服务器
|
||||
```bash
|
||||
# 方式1:使用uvicorn直接启动
|
||||
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||||
|
||||
# 方式2:使用make命令
|
||||
make run-dev
|
||||
|
||||
# 方式3:使用启动脚本
|
||||
./scripts/start_dev.sh
|
||||
```
|
||||
|
||||
### 4.3 验证服务启动
|
||||
```bash
|
||||
# 检查健康状态
|
||||
curl http://localhost:8000/health
|
||||
|
||||
# 查看API文档
|
||||
open http://localhost:8000/docs # Swagger UI
|
||||
open http://localhost:8000/redoc # ReDoc
|
||||
```
|
||||
|
||||
## 5. 开发工作流
|
||||
|
||||
### 5.1 创建功能分支
|
||||
```bash
|
||||
# 基于develop创建功能分支
|
||||
git checkout develop
|
||||
git pull origin develop
|
||||
git checkout -b feature/your-module-name
|
||||
|
||||
# 例如:
|
||||
git checkout -b feature/auth
|
||||
git checkout -b feature/user
|
||||
git checkout -b feature/course
|
||||
```
|
||||
|
||||
### 5.2 代码开发流程
|
||||
```bash
|
||||
# 1. 编写代码
|
||||
# 2. 格式化代码
|
||||
make format
|
||||
|
||||
# 3. 检查代码质量
|
||||
make lint
|
||||
|
||||
# 4. 类型检查
|
||||
make type-check
|
||||
|
||||
# 5. 运行测试
|
||||
make test
|
||||
|
||||
# 或一次性运行所有检查
|
||||
make check-all
|
||||
```
|
||||
|
||||
### 5.3 提交代码
|
||||
```bash
|
||||
# 添加更改
|
||||
git add .
|
||||
|
||||
# 提交(会自动运行pre-commit hooks)
|
||||
git commit -m "feat(auth): 实现用户登录功能"
|
||||
|
||||
# 推送到远程
|
||||
git push origin feature/your-module-name
|
||||
```
|
||||
|
||||
### 5.4 创建Pull Request
|
||||
1. 在GitHub/GitLab上创建PR
|
||||
2. 填写PR模板
|
||||
3. 等待代码审查
|
||||
4. 合并到develop分支
|
||||
|
||||
## 6. 模块开发指南
|
||||
|
||||
### 6.1 创建新模块的步骤
|
||||
|
||||
以用户模块为例:
|
||||
|
||||
1. **创建模型文件**
|
||||
```python
|
||||
# app/models/user.py
|
||||
from sqlalchemy import Column, String, Boolean
|
||||
from app.models.base import BaseModel, AuditMixin
|
||||
|
||||
class User(BaseModel, AuditMixin):
|
||||
__tablename__ = "users"
|
||||
|
||||
username = Column(String(50), unique=True, nullable=False)
|
||||
email = Column(String(100), unique=True, nullable=False)
|
||||
password_hash = Column(String(200), nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
```
|
||||
|
||||
2. **创建Schema文件**
|
||||
```python
|
||||
# app/schemas/user.py
|
||||
from pydantic import EmailStr, validator
|
||||
from app.schemas.base import BaseSchema, TimestampMixin, IDMixin
|
||||
|
||||
class UserBase(BaseSchema):
|
||||
username: str
|
||||
email: EmailStr
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
@validator('password')
|
||||
def validate_password(cls, v):
|
||||
# 密码验证逻辑
|
||||
return v
|
||||
|
||||
class UserUpdate(BaseSchema):
|
||||
email: Optional[EmailStr] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
class UserInDB(UserBase, IDMixin, TimestampMixin):
|
||||
is_active: bool
|
||||
```
|
||||
|
||||
3. **创建服务文件**
|
||||
```python
|
||||
# app/services/user_service.py
|
||||
from app.services.base_service import BaseService
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
class UserService(BaseService[User, UserCreate, UserUpdate]):
|
||||
def __init__(self, db):
|
||||
super().__init__(User, db)
|
||||
|
||||
# 添加特定的业务逻辑
|
||||
```
|
||||
|
||||
4. **创建API路由**
|
||||
```python
|
||||
# app/api/v1/users.py
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.services.user_service import UserService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/users")
|
||||
async def get_users(
|
||||
db = Depends(get_db),
|
||||
current_user = Depends(get_current_user)
|
||||
):
|
||||
service = UserService(db)
|
||||
return await service.get_multi()
|
||||
```
|
||||
|
||||
5. **注册路由**
|
||||
```python
|
||||
# app/api/v1/__init__.py
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1 import users
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||
```
|
||||
|
||||
### 6.2 测试开发
|
||||
|
||||
1. **创建测试文件**
|
||||
```python
|
||||
# tests/unit/test_user_service.py
|
||||
import pytest
|
||||
from app.services.user_service import UserService
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_user(db_session):
|
||||
service = UserService(db_session)
|
||||
# 测试逻辑
|
||||
```
|
||||
|
||||
2. **运行测试**
|
||||
```bash
|
||||
# 运行所有测试
|
||||
pytest
|
||||
|
||||
# 运行特定模块测试
|
||||
pytest tests/unit/test_user_service.py
|
||||
|
||||
# 运行并查看覆盖率
|
||||
pytest --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
## 7. 调试技巧
|
||||
|
||||
### 7.1 使用IPython进行交互式调试
|
||||
```bash
|
||||
# 安装ipython
|
||||
pip install ipython
|
||||
|
||||
# 在代码中添加断点
|
||||
import IPython; IPython.embed()
|
||||
```
|
||||
|
||||
### 7.2 使用VSCode调试
|
||||
创建 `.vscode/launch.json`:
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Python: FastAPI",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"module": "uvicorn",
|
||||
"args": [
|
||||
"app.main:app",
|
||||
"--reload",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--port",
|
||||
"8000"
|
||||
],
|
||||
"jinja": true,
|
||||
"justMyCode": true,
|
||||
"env": {
|
||||
"PYTHONPATH": "${workspaceFolder}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 7.3 查看SQL语句
|
||||
```python
|
||||
# 在.env中设置
|
||||
DEBUG=true
|
||||
|
||||
# 这会在控制台输出所有SQL语句
|
||||
```
|
||||
|
||||
## 8. 常见问题解决
|
||||
|
||||
### 8.1 数据库连接失败
|
||||
```bash
|
||||
# 检查MySQL服务状态
|
||||
sudo systemctl status mysql
|
||||
|
||||
# 检查连接
|
||||
mysql -h localhost -u root -p
|
||||
|
||||
# 检查.env中的DATABASE_URL配置
|
||||
```
|
||||
|
||||
### 8.2 依赖冲突
|
||||
```bash
|
||||
# 清理并重新安装
|
||||
pip uninstall -y -r requirements/base.txt
|
||||
pip install -r requirements/base.txt
|
||||
```
|
||||
|
||||
### 8.3 迁移失败
|
||||
```bash
|
||||
# 查看当前迁移状态
|
||||
alembic current
|
||||
|
||||
# 降级到前一个版本
|
||||
alembic downgrade -1
|
||||
|
||||
# 查看迁移历史
|
||||
alembic history
|
||||
```
|
||||
|
||||
### 8.4 Redis连接问题
|
||||
```bash
|
||||
# 测试Redis连接
|
||||
redis-cli ping
|
||||
|
||||
# 检查Redis配置
|
||||
redis-cli CONFIG GET bind
|
||||
redis-cli CONFIG GET protected-mode
|
||||
```
|
||||
|
||||
## 9. 部署准备
|
||||
|
||||
### 9.1 生产环境配置
|
||||
```bash
|
||||
# 使用生产配置
|
||||
cp .env.example .env.prod
|
||||
|
||||
# 编辑生产配置
|
||||
# DEBUG=false
|
||||
# LOG_LEVEL=WARNING
|
||||
```
|
||||
|
||||
### 9.2 构建Docker镜像
|
||||
```bash
|
||||
# 构建镜像
|
||||
docker build -t kaopeilian-backend:latest .
|
||||
|
||||
# 运行容器
|
||||
docker run -d \
|
||||
--name kaopeilian-backend \
|
||||
-p 8000:8000 \
|
||||
--env-file .env.prod \
|
||||
kaopeilian-backend:latest
|
||||
```
|
||||
|
||||
### 9.3 性能优化
|
||||
```bash
|
||||
# 使用生产服务器
|
||||
gunicorn app.main:app \
|
||||
-w 4 \
|
||||
-k uvicorn.workers.UvicornWorker \
|
||||
--bind 0.0.0.0:8000
|
||||
```
|
||||
|
||||
## 10. 团队协作建议
|
||||
|
||||
### 10.1 代码审查重点
|
||||
- API接口是否符合RESTful规范
|
||||
- 是否有适当的错误处理
|
||||
- 是否有完整的日志记录
|
||||
- 测试覆盖率是否达标
|
||||
- 是否有安全漏洞
|
||||
|
||||
### 10.2 文档要求
|
||||
- 每个API必须有完整的文档字符串
|
||||
- 复杂的业务逻辑需要添加注释
|
||||
- 更新README.md中的相关说明
|
||||
- 在CHANGELOG.md中记录重要更改
|
||||
|
||||
### 10.3 沟通机制
|
||||
- 每日站会同步进展
|
||||
- 使用Issue跟踪问题
|
||||
- PR中详细描述更改内容
|
||||
- 遇到阻塞及时沟通
|
||||
|
||||
## 11. 资源链接
|
||||
|
||||
- [FastAPI官方文档](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy文档](https://docs.sqlalchemy.org/)
|
||||
- [Alembic文档](https://alembic.sqlalchemy.org/)
|
||||
- [Pydantic文档](https://pydantic-docs.helpmanual.io/)
|
||||
- [pytest文档](https://docs.pytest.org/)
|
||||
- [项目Wiki](项目Wiki链接)
|
||||
- [API文档](http://localhost:8000/docs)
|
||||
|
||||
## 12. 下一步
|
||||
|
||||
1. 阅读[开发规范文档](./开发规范文档.md)
|
||||
2. 查看[模块分工指南](./模块分工指南.md)
|
||||
3. 了解[协作机制设计](./协作机制设计.md)
|
||||
4. 开始你负责模块的开发!
|
||||
|
||||
如有任何问题,请在项目Issue中提出或联系技术负责人。
|
||||
|
||||
祝开发顺利! 🚀
|
||||
571
docs/规划/后端开发拆分策略/模块分工指南.md
Normal file
571
docs/规划/后端开发拆分策略/模块分工指南.md
Normal file
@@ -0,0 +1,571 @@
|
||||
# 考培练系统后端模块分工指南
|
||||
|
||||
## 1. 模块划分总览
|
||||
|
||||
### 核心业务模块
|
||||
| 模块名称 | Agent代号 | 负责范围 | 依赖模块 |
|
||||
|---------|----------|---------|----------|
|
||||
| 认证授权模块 | Agent-Auth | 登录、注册、权限管理、Token管理 | - |
|
||||
| 用户管理模块 | Agent-User | 用户CRUD、个人信息、团队管理 | Auth |
|
||||
| 课程管理模块 | Agent-Course | 课程CRUD、资料管理、成长路径 | Auth, User |
|
||||
| 考试模块 | Agent-Exam | 动态考试、成绩管理、错题分析 | Auth, User, Dify |
|
||||
| AI陪练模块 | Agent-Training | 陪练场景、实时对话、陪练记录 | Auth, User, Coze |
|
||||
| 数据分析模块 | Agent-Analytics | 统计分析、数据可视化、报表生成 | Auth, User, Exam, Training |
|
||||
| 系统管理模块 | Agent-Admin | 系统配置、日志管理、岗位管理 | Auth, User |
|
||||
|
||||
### AI集成模块
|
||||
| 模块名称 | Agent代号 | 负责范围 | 对接平台 |
|
||||
|---------|----------|---------|----------|
|
||||
| Coze集成服务 | Agent-Coze | Coze API封装、会话管理、消息处理 | Coze平台 |
|
||||
| Dify集成服务 | Agent-Dify | Dify工作流调用、知识库查询 | Dify平台 |
|
||||
|
||||
## 2. 详细模块说明
|
||||
|
||||
### 2.1 Agent-Auth(认证授权模块)
|
||||
|
||||
**负责人**: 子Agent-1
|
||||
|
||||
**主要职责**:
|
||||
- 用户登录/登出
|
||||
- 用户注册
|
||||
- JWT Token生成与验证
|
||||
- 权限检查中间件
|
||||
- 密码重置功能
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── core/
|
||||
│ ├── security.py # JWT处理、密码加密
|
||||
│ └── dependencies.py # 认证依赖注入
|
||||
├── models/
|
||||
│ └── user.py # User模型(仅认证相关字段)
|
||||
├── schemas/
|
||||
│ └── auth.py # 认证相关的Pydantic模型
|
||||
├── services/
|
||||
│ └── auth_service.py # 认证业务逻辑
|
||||
└── api/v1/
|
||||
└── auth.py # 认证相关API路由
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
POST /api/v1/auth/login # 用户登录
|
||||
POST /api/v1/auth/register # 用户注册
|
||||
POST /api/v1/auth/logout # 用户登出
|
||||
POST /api/v1/auth/refresh # 刷新Token
|
||||
POST /api/v1/auth/reset-password # 重置密码
|
||||
```
|
||||
|
||||
**与其他模块的接口**:
|
||||
```python
|
||||
# 提供给其他模块的依赖注入
|
||||
from app.api.deps import get_current_user, require_admin
|
||||
|
||||
@router.get("/protected")
|
||||
async def protected_route(current_user: User = Depends(get_current_user)):
|
||||
return {"user": current_user}
|
||||
```
|
||||
|
||||
### 2.2 Agent-User(用户管理模块)
|
||||
|
||||
**负责人**: 子Agent-2
|
||||
|
||||
**主要职责**:
|
||||
- 用户信息CRUD
|
||||
- 个人资料管理
|
||||
- 团队/部门管理
|
||||
- 用户角色分配
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── models/
|
||||
│ ├── user.py # User模型(完整)
|
||||
│ └── team.py # Team/Department模型
|
||||
├── schemas/
|
||||
│ ├── user.py # 用户相关Schema
|
||||
│ └── team.py # 团队相关Schema
|
||||
├── services/
|
||||
│ ├── user_service.py # 用户业务逻辑
|
||||
│ └── team_service.py # 团队业务逻辑
|
||||
└── api/v1/
|
||||
└── users.py # 用户管理API
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
GET /api/v1/users # 获取用户列表
|
||||
GET /api/v1/users/{id} # 获取用户详情
|
||||
PUT /api/v1/users/{id} # 更新用户信息
|
||||
DELETE /api/v1/users/{id} # 删除用户
|
||||
GET /api/v1/users/me # 获取当前用户信息
|
||||
PUT /api/v1/users/me # 更新当前用户信息
|
||||
|
||||
GET /api/v1/teams # 获取团队列表
|
||||
POST /api/v1/teams # 创建团队
|
||||
PUT /api/v1/teams/{id} # 更新团队
|
||||
POST /api/v1/teams/{id}/members # 添加团队成员
|
||||
```
|
||||
|
||||
### 2.3 Agent-Course(课程管理模块)
|
||||
|
||||
**负责人**: 子Agent-3
|
||||
|
||||
**主要职责**:
|
||||
- 课程CRUD操作
|
||||
- 课程资料管理
|
||||
- 知识点管理
|
||||
- 成长路径配置
|
||||
- 课程分配
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── models/
|
||||
│ ├── course.py # Course模型
|
||||
│ ├── material.py # 课程资料模型
|
||||
│ └── growth_path.py # 成长路径模型
|
||||
├── schemas/
|
||||
│ ├── course.py # 课程相关Schema
|
||||
│ └── growth_path.py # 成长路径Schema
|
||||
├── services/
|
||||
│ ├── course_service.py # 课程业务逻辑
|
||||
│ └── growth_path_service.py # 成长路径逻辑
|
||||
└── api/v1/
|
||||
└── courses.py # 课程管理API
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
# 课程管理
|
||||
GET /api/v1/courses # 获取课程列表
|
||||
POST /api/v1/courses # 创建课程
|
||||
GET /api/v1/courses/{id} # 获取课程详情
|
||||
PUT /api/v1/courses/{id} # 更新课程
|
||||
DELETE /api/v1/courses/{id} # 删除课程
|
||||
|
||||
# 课程资料
|
||||
POST /api/v1/courses/{id}/materials # 上传资料
|
||||
GET /api/v1/courses/{id}/materials # 获取资料列表
|
||||
DELETE /api/v1/courses/{id}/materials/{material_id} # 删除资料
|
||||
|
||||
# 成长路径
|
||||
GET /api/v1/growth-paths # 获取成长路径列表
|
||||
POST /api/v1/growth-paths # 创建成长路径
|
||||
PUT /api/v1/growth-paths/{id} # 更新成长路径
|
||||
```
|
||||
|
||||
### 2.4 Agent-Exam(考试模块)
|
||||
|
||||
**负责人**: 子Agent-4
|
||||
|
||||
**主要职责**:
|
||||
- 动态生成考题(调用Dify)
|
||||
- 考试流程管理
|
||||
- 成绩计算与存储
|
||||
- 错题本管理
|
||||
- 考试报告生成
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── models/
|
||||
│ ├── exam.py # Exam模型
|
||||
│ ├── question.py # Question模型
|
||||
│ └── exam_record.py # 考试记录模型
|
||||
├── schemas/
|
||||
│ ├── exam.py # 考试相关Schema
|
||||
│ └── question.py # 题目相关Schema
|
||||
├── services/
|
||||
│ ├── exam_service.py # 考试业务逻辑
|
||||
│ └── question_service.py # 题目业务逻辑
|
||||
└── api/v1/
|
||||
└── exams.py # 考试相关API
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
# 考试管理
|
||||
POST /api/v1/exams/start # 开始考试
|
||||
POST /api/v1/exams/submit # 提交答案
|
||||
GET /api/v1/exams/{id} # 获取考试详情
|
||||
GET /api/v1/exams/records # 获取考试记录
|
||||
|
||||
# 成绩查询
|
||||
GET /api/v1/scores # 获取成绩列表
|
||||
GET /api/v1/scores/{id} # 获取成绩详情
|
||||
GET /api/v1/scores/statistics # 成绩统计
|
||||
|
||||
# 错题管理
|
||||
GET /api/v1/mistakes # 获取错题列表
|
||||
POST /api/v1/mistakes/practice # 错题重练
|
||||
```
|
||||
|
||||
### 2.5 Agent-Training(AI陪练模块)
|
||||
|
||||
**负责人**: 子Agent-5
|
||||
|
||||
**主要职责**:
|
||||
- 陪练场景管理
|
||||
- WebSocket实时对话
|
||||
- 语音处理(TTS/ASR)
|
||||
- 陪练记录管理
|
||||
- 陪练报告生成
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── models/
|
||||
│ ├── training_scene.py # 陪练场景模型
|
||||
│ ├── training_record.py # 陪练记录模型
|
||||
│ └── training_plan.py # 陪练计划模型
|
||||
├── schemas/
|
||||
│ ├── training.py # 陪练相关Schema
|
||||
│ └── training_plan.py # 计划相关Schema
|
||||
├── services/
|
||||
│ ├── training_service.py # 陪练业务逻辑
|
||||
│ └── training_plan_service.py # 计划业务逻辑
|
||||
└── api/v1/
|
||||
├── training.py # 陪练相关API
|
||||
└── websocket.py # WebSocket处理
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
# 陪练场景管理
|
||||
GET /api/v1/training-scenes # 获取场景列表
|
||||
POST /api/v1/training-scenes # 创建场景
|
||||
PUT /api/v1/training-scenes/{id} # 更新场景
|
||||
|
||||
# 陪练计划
|
||||
GET /api/v1/training-plans # 获取计划列表
|
||||
POST /api/v1/training-plans # 创建计划
|
||||
POST /api/v1/training-plans/{id}/assign # 分配计划
|
||||
|
||||
# 陪练会话
|
||||
WS /ws/v1/training/{scene_id} # WebSocket陪练
|
||||
POST /api/v1/training/start # 开始陪练
|
||||
POST /api/v1/training/end # 结束陪练
|
||||
|
||||
# 陪练记录
|
||||
GET /api/v1/training-records # 获取记录列表
|
||||
GET /api/v1/training-records/{id} # 获取记录详情
|
||||
```
|
||||
|
||||
### 2.6 Agent-Analytics(数据分析模块)
|
||||
|
||||
**负责人**: 子Agent-6
|
||||
|
||||
**主要职责**:
|
||||
- 学习数据统计
|
||||
- 考试成绩分析
|
||||
- 陪练效果分析
|
||||
- 能力评估报告
|
||||
- 数据可视化
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/
|
||||
├── schemas/
|
||||
│ └── analytics.py # 分析相关Schema
|
||||
├── services/
|
||||
│ ├── analytics_service.py # 分析业务逻辑
|
||||
│ └── report_service.py # 报告生成逻辑
|
||||
└── api/v1/
|
||||
└── analytics.py # 分析相关API
|
||||
```
|
||||
|
||||
**API接口**:
|
||||
```
|
||||
# 整体统计
|
||||
GET /api/v1/analytics/overview # 总览数据
|
||||
GET /api/v1/analytics/trends # 趋势分析
|
||||
|
||||
# 学员分析
|
||||
GET /api/v1/analytics/users/{id}/ability # 能力雷达图
|
||||
GET /api/v1/analytics/users/{id}/progress # 学习进度
|
||||
GET /api/v1/analytics/users/{id}/report # 个人报告
|
||||
|
||||
# 团队分析
|
||||
GET /api/v1/analytics/teams/{id}/overview # 团队概况
|
||||
GET /api/v1/analytics/teams/{id}/ranking # 团队排名
|
||||
```
|
||||
|
||||
### 2.7 Agent-Coze(Coze集成服务)
|
||||
|
||||
**负责人**: 子Agent-7
|
||||
|
||||
**主要职责**:
|
||||
- Coze API客户端封装
|
||||
- 会话管理
|
||||
- 消息流处理
|
||||
- 错误重试机制
|
||||
- 响应数据转换
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/services/ai/coze/
|
||||
├── __init__.py
|
||||
├── client.py # Coze客户端
|
||||
├── training.py # 陪练相关功能
|
||||
├── chat.py # 对话相关功能
|
||||
├── models.py # Coze数据模型
|
||||
└── exceptions.py # Coze异常处理
|
||||
```
|
||||
|
||||
**提供的服务接口**:
|
||||
```python
|
||||
class CozeService:
|
||||
async def create_training_session(self, bot_id: str, user_id: int)
|
||||
async def send_message(self, session_id: str, content: str)
|
||||
async def stream_chat(self, session_id: str, content: str)
|
||||
async def end_session(self, session_id: str)
|
||||
async def get_evaluation_report(self, session_id: str)
|
||||
```
|
||||
|
||||
**对外API(统一网关,供前端与第三方服务解耦)**:
|
||||
```
|
||||
# 课程对话(与课程对话页 /trainee/chat-course 使用)
|
||||
POST /api/v1/course-chat/sessions # 创建课程对话会话(入参:course_id,可选:bot_id 覆盖)
|
||||
POST /api/v1/course-chat/messages # 发送消息(入参:session_id, content, stream?bool)
|
||||
WS /ws/v1/course-chat/{session_id} # 可选:流式对话通道(文本/事件流)
|
||||
|
||||
# 陪练语音会话(AI陪练会话页 /trainee/ai-practice 使用)
|
||||
POST /api/v1/training/sessions # 创建陪练会话(入参:scene_id 或 bot_id,user_context 可选)
|
||||
POST /api/v1/training/sessions/{id}/end # 结束陪练会话
|
||||
WS /ws/v1/training/{session_id} # 语音/文本实时通话(沿用现有 coze-chat-backend 接口形式)
|
||||
|
||||
# 配置(统一环境变量)
|
||||
# COZE_TRAINING_BOT_ID (陪练用Bot)
|
||||
# COZE_CHAT_BOT_ID (课程对话用Bot)
|
||||
```
|
||||
|
||||
> 说明:以上为网关层标准,内部由 `Agent-Coze` 适配既有 `coze-chat-backend` 能力(接口形同,仅切换 bot_id)。
|
||||
|
||||
### 2.8 Agent-Dify(Dify集成服务)
|
||||
|
||||
**负责人**: 子Agent-8
|
||||
|
||||
**主要职责**:
|
||||
- Dify API客户端封装
|
||||
- 工作流调用
|
||||
- 知识库查询
|
||||
- 能力评估
|
||||
- 课程推荐
|
||||
|
||||
**核心文件**:
|
||||
```
|
||||
app/services/ai/dify/
|
||||
├── __init__.py
|
||||
├── client.py # Dify客户端
|
||||
├── exam.py # 考试相关功能
|
||||
├── assessment.py # 评估相关功能
|
||||
├── recommend.py # 推荐相关功能
|
||||
├── models.py # Dify数据模型
|
||||
└── exceptions.py # Dify异常处理
|
||||
```
|
||||
|
||||
**提供的服务接口**:
|
||||
```python
|
||||
class DifyService:
|
||||
async def generate_exam_questions(self, course_id: int, count: int)
|
||||
async def evaluate_ability(self, user_id: int, audio_data: bytes)
|
||||
async def recommend_courses(self, user_id: int, weak_points: List[str])
|
||||
async def query_knowledge_base(self, query: str)
|
||||
```
|
||||
|
||||
**对外API(统一网关,供前端与第三方服务解耦)**:
|
||||
```
|
||||
# 动态考试(与 /exam/practice、/trainee/score-report 匹配)
|
||||
POST /api/v1/exams/start # 启动动态考卷生成(入参:course_id, count,可选:difficulty/tags)
|
||||
POST /api/v1/exams/submit # 提交答案
|
||||
GET /api/v1/exams/{id} # 获取考试详情/题目
|
||||
GET /api/v1/exams/records # 获取考试记录
|
||||
|
||||
# 知识拆解(课程资料上传后触发/手动重分析,供课程中心与知识点管理)
|
||||
POST /api/v1/knowledge/decompose # 文档/媒体知识拆解(入参:course_id, file_url 或 material_id)
|
||||
GET /api/v1/courses/{id}/knowledge-points # 获取课程知识点清单
|
||||
|
||||
# 能力评估与推荐(用于成长路径/个性化推荐)
|
||||
POST /api/v1/assessment/ability # 上传音频或引用外部音频记录,返回能力弱项标签
|
||||
POST /api/v1/recommend/courses # 根据弱项标签返回推荐课程
|
||||
```
|
||||
|
||||
> 说明:网关层对接既有 `ExamsSystem` 与 `Dify` 工作流,保持前端稳定接口。
|
||||
|
||||
## 3. 模块间协作规则
|
||||
|
||||
### 3.1 依赖关系原则
|
||||
1. **单向依赖**: 模块间只能单向依赖,避免循环依赖
|
||||
2. **接口隔离**: 通过定义清晰的接口进行通信
|
||||
3. **最小依赖**: 只依赖必要的模块,减少耦合
|
||||
|
||||
### 3.2 数据共享机制
|
||||
```python
|
||||
# app/core/context.py
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Any
|
||||
|
||||
@dataclass
|
||||
class SharedContext:
|
||||
"""模块间共享的上下文信息"""
|
||||
user_info: Dict[str, Any]
|
||||
request_id: str
|
||||
trace_id: str
|
||||
|
||||
# 在请求中传递上下文
|
||||
async def some_api_handler(
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
context = SharedContext(
|
||||
user_info={"id": current_user.id, "role": current_user.role},
|
||||
request_id=request.state.request_id,
|
||||
trace_id=request.state.trace_id
|
||||
)
|
||||
# 传递给服务层
|
||||
result = await service.process(context, data)
|
||||
```
|
||||
|
||||
### 3.3 事件通知机制
|
||||
```python
|
||||
# app/core/events.py
|
||||
from enum import Enum
|
||||
from typing import Any, Dict
|
||||
|
||||
class EventType(Enum):
|
||||
USER_CREATED = "user.created"
|
||||
COURSE_COMPLETED = "course.completed"
|
||||
EXAM_FINISHED = "exam.finished"
|
||||
TRAINING_COMPLETED = "training.completed"
|
||||
|
||||
class EventBus:
|
||||
"""简单的事件总线实现"""
|
||||
def __init__(self):
|
||||
self._handlers = {}
|
||||
|
||||
def subscribe(self, event_type: EventType, handler):
|
||||
if event_type not in self._handlers:
|
||||
self._handlers[event_type] = []
|
||||
self._handlers[event_type].append(handler)
|
||||
|
||||
async def publish(self, event_type: EventType, data: Dict[str, Any]):
|
||||
if event_type in self._handlers:
|
||||
for handler in self._handlers[event_type]:
|
||||
await handler(data)
|
||||
|
||||
# 使用示例
|
||||
event_bus = EventBus()
|
||||
|
||||
# 在用户模块中发布事件
|
||||
await event_bus.publish(EventType.USER_CREATED, {"user_id": user.id})
|
||||
|
||||
# 在分析模块中订阅事件
|
||||
async def handle_user_created(data: Dict[str, Any]):
|
||||
user_id = data["user_id"]
|
||||
# 初始化用户的分析数据
|
||||
await analytics_service.init_user_analytics(user_id)
|
||||
|
||||
event_bus.subscribe(EventType.USER_CREATED, handle_user_created)
|
||||
```
|
||||
|
||||
## 4. 开发时序安排
|
||||
|
||||
### 第一批次(基础模块)
|
||||
1. **Agent-Auth**: 最先开发,其他模块都依赖认证
|
||||
2. **Agent-User**: 紧随其后,提供用户基础数据
|
||||
|
||||
### 第二批次(AI集成)
|
||||
3. **Agent-Coze**: 为陪练模块提供支持
|
||||
4. **Agent-Dify**: 为考试模块提供支持
|
||||
|
||||
### 第三批次(业务模块)
|
||||
5. **Agent-Course**: 课程管理功能
|
||||
6. **Agent-Exam**: 考试功能(依赖Dify)
|
||||
7. **Agent-Training**: 陪练功能(依赖Coze)
|
||||
|
||||
### 第四批次(高级功能)
|
||||
8. **Agent-Analytics**: 数据分析(依赖其他业务模块的数据)
|
||||
9. **Agent-Admin**: 系统管理功能
|
||||
|
||||
## 5. 接口文档规范
|
||||
|
||||
每个模块必须提供完整的接口文档,格式如下:
|
||||
|
||||
```yaml
|
||||
# api_docs/auth.yaml
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: 认证授权模块API
|
||||
version: 1.0.0
|
||||
|
||||
paths:
|
||||
/api/v1/auth/login:
|
||||
post:
|
||||
summary: 用户登录
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
description: 用户名或邮箱
|
||||
password:
|
||||
type: string
|
||||
description: 密码
|
||||
required:
|
||||
- username
|
||||
- password
|
||||
responses:
|
||||
200:
|
||||
description: 登录成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: integer
|
||||
example: 200
|
||||
message:
|
||||
type: string
|
||||
example: success
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
access_token:
|
||||
type: string
|
||||
refresh_token:
|
||||
type: string
|
||||
user:
|
||||
$ref: '#/components/schemas/User'
|
||||
```
|
||||
|
||||
## 6. 模块交付标准
|
||||
|
||||
每个模块完成时必须包含:
|
||||
|
||||
1. **源代码**
|
||||
- 符合编码规范
|
||||
- 包含完整的类型注解
|
||||
- 有充分的注释
|
||||
|
||||
2. **测试代码**
|
||||
- 单元测试覆盖率 > 80%
|
||||
- 包含集成测试用例
|
||||
- 测试数据准备脚本
|
||||
|
||||
3. **文档**
|
||||
- API接口文档(OpenAPI格式)
|
||||
- 模块设计文档
|
||||
- 部署配置说明
|
||||
|
||||
4. **示例**
|
||||
- API调用示例
|
||||
- 配置文件示例
|
||||
- 常见问题解答
|
||||
|
||||
1282
docs/规划/后端开发拆分策略/统一基础代码.md
Normal file
1282
docs/规划/后端开发拆分策略/统一基础代码.md
Normal file
File diff suppressed because it is too large
Load Diff
925
docs/规划/后端开发拆分策略/质量保证机制.md
Normal file
925
docs/规划/后端开发拆分策略/质量保证机制.md
Normal file
@@ -0,0 +1,925 @@
|
||||
# 考培练系统后端质量保证机制
|
||||
|
||||
## 1. 代码质量保证
|
||||
|
||||
### 1.1 自动化代码检查
|
||||
```yaml
|
||||
# .pre-commit-config.yaml
|
||||
repos:
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 23.3.0
|
||||
hooks:
|
||||
- id: black
|
||||
language_version: python3.8
|
||||
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.12.0
|
||||
hooks:
|
||||
- id: isort
|
||||
args: ["--profile", "black"]
|
||||
|
||||
- repo: https://github.com/pycqa/flake8
|
||||
rev: 6.0.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
args: ["--max-line-length", "88", "--extend-ignore", "E203"]
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.3.0
|
||||
hooks:
|
||||
- id: mypy
|
||||
additional_dependencies: [types-all]
|
||||
```
|
||||
|
||||
### 1.2 代码复杂度控制
|
||||
```python
|
||||
# setup.cfg
|
||||
[flake8]
|
||||
max-line-length = 88
|
||||
max-complexity = 10 # 圈复杂度限制
|
||||
extend-ignore = E203, W503
|
||||
exclude = .git,__pycache__,venv,migrations
|
||||
|
||||
[mypy]
|
||||
python_version = 3.8
|
||||
warn_return_any = True
|
||||
warn_unused_configs = True
|
||||
disallow_untyped_defs = True
|
||||
disallow_incomplete_defs = True
|
||||
check_untyped_defs = True
|
||||
disallow_untyped_decorators = True
|
||||
no_implicit_optional = True
|
||||
warn_redundant_casts = True
|
||||
warn_unused_ignores = True
|
||||
warn_no_return = True
|
||||
warn_unreachable = True
|
||||
strict_equality = True
|
||||
```
|
||||
|
||||
## 2. 测试策略
|
||||
|
||||
### 2.1 测试金字塔
|
||||
```
|
||||
/\
|
||||
/ \ 端到端测试 (10%)
|
||||
/ \ - 完整业务流程测试
|
||||
/ \- UI自动化测试
|
||||
/--------\
|
||||
/ \ 集成测试 (30%)
|
||||
/ \- API测试
|
||||
/ \- 数据库集成测试
|
||||
/ \- 第三方服务集成测试
|
||||
/------------------\
|
||||
单元测试 (60%)
|
||||
- 业务逻辑测试
|
||||
- 工具函数测试
|
||||
- 数据验证测试
|
||||
```
|
||||
|
||||
### 2.2 单元测试规范
|
||||
```python
|
||||
# tests/unit/test_user_service.py
|
||||
import pytest
|
||||
from unittest.mock import Mock, AsyncMock
|
||||
from app.services.user_service import UserService
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
|
||||
class TestUserService:
|
||||
"""用户服务单元测试"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
"""模拟数据库会话"""
|
||||
return AsyncMock()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_logger(self):
|
||||
"""模拟日志器"""
|
||||
return Mock()
|
||||
|
||||
@pytest.fixture
|
||||
def user_service(self, mock_db, mock_logger):
|
||||
"""创建用户服务实例"""
|
||||
return UserService(db=mock_db, logger=mock_logger)
|
||||
|
||||
async def test_create_user_success(self, user_service, mock_db):
|
||||
"""测试成功创建用户"""
|
||||
# 准备测试数据
|
||||
user_data = UserCreate(
|
||||
username="testuser",
|
||||
email="test@example.com",
|
||||
password="securepassword"
|
||||
)
|
||||
|
||||
# 配置mock
|
||||
mock_db.execute.return_value.scalar_one_or_none.return_value = None
|
||||
mock_db.commit.return_value = None
|
||||
|
||||
# 执行测试
|
||||
result = await user_service.create_user(user_data)
|
||||
|
||||
# 验证结果
|
||||
assert result is not None
|
||||
assert result.username == user_data.username
|
||||
assert result.email == user_data.email
|
||||
mock_db.commit.assert_called_once()
|
||||
|
||||
async def test_create_user_duplicate_username(self, user_service, mock_db):
|
||||
"""测试用户名重复的情况"""
|
||||
# 准备测试数据
|
||||
user_data = UserCreate(
|
||||
username="existinguser",
|
||||
email="new@example.com",
|
||||
password="password"
|
||||
)
|
||||
|
||||
# 配置mock - 模拟用户已存在
|
||||
mock_db.execute.return_value.scalar_one_or_none.return_value = User(
|
||||
id=1,
|
||||
username="existinguser"
|
||||
)
|
||||
|
||||
# 执行测试并验证异常
|
||||
with pytest.raises(ValueError, match="用户名已存在"):
|
||||
await user_service.create_user(user_data)
|
||||
|
||||
# 验证未提交事务
|
||||
mock_db.commit.assert_not_called()
|
||||
```
|
||||
|
||||
### 2.3 集成测试规范
|
||||
```python
|
||||
# tests/integration/test_auth_flow.py
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
|
||||
@pytest.mark.integration
|
||||
class TestAuthFlow:
|
||||
"""认证流程集成测试"""
|
||||
|
||||
async def test_complete_auth_flow(
|
||||
self,
|
||||
async_client: AsyncClient,
|
||||
db_session: AsyncSession
|
||||
):
|
||||
"""测试完整的认证流程"""
|
||||
# 1. 注册新用户
|
||||
register_data = {
|
||||
"username": "newuser",
|
||||
"email": "newuser@example.com",
|
||||
"password": "StrongPassword123!"
|
||||
}
|
||||
|
||||
response = await async_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json=register_data
|
||||
)
|
||||
assert response.status_code == 201
|
||||
user_data = response.json()["data"]
|
||||
assert user_data["username"] == register_data["username"]
|
||||
|
||||
# 2. 登录
|
||||
login_data = {
|
||||
"username": register_data["username"],
|
||||
"password": register_data["password"]
|
||||
}
|
||||
|
||||
response = await async_client.post(
|
||||
"/api/v1/auth/login",
|
||||
json=login_data
|
||||
)
|
||||
assert response.status_code == 200
|
||||
tokens = response.json()["data"]
|
||||
assert "access_token" in tokens
|
||||
assert "refresh_token" in tokens
|
||||
|
||||
# 3. 访问受保护的端点
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
response = await async_client.get(
|
||||
"/api/v1/users/me",
|
||||
headers=headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data"]["username"] == register_data["username"]
|
||||
|
||||
# 4. 刷新Token
|
||||
refresh_data = {"refresh_token": tokens["refresh_token"]}
|
||||
response = await async_client.post(
|
||||
"/api/v1/auth/refresh",
|
||||
json=refresh_data
|
||||
)
|
||||
assert response.status_code == 200
|
||||
new_tokens = response.json()["data"]
|
||||
assert new_tokens["access_token"] != tokens["access_token"]
|
||||
```
|
||||
|
||||
### 2.4 性能测试
|
||||
```python
|
||||
# tests/performance/test_api_performance.py
|
||||
import pytest
|
||||
import asyncio
|
||||
import time
|
||||
from httpx import AsyncClient
|
||||
from statistics import mean, stdev
|
||||
|
||||
@pytest.mark.performance
|
||||
class TestAPIPerformance:
|
||||
"""API性能测试"""
|
||||
|
||||
async def test_login_performance(self, async_client: AsyncClient):
|
||||
"""测试登录接口性能"""
|
||||
login_data = {
|
||||
"username": "perftest",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
# 预热
|
||||
for _ in range(5):
|
||||
await async_client.post("/api/v1/auth/login", json=login_data)
|
||||
|
||||
# 性能测试
|
||||
response_times = []
|
||||
concurrent_requests = 10
|
||||
total_requests = 100
|
||||
|
||||
async def make_request():
|
||||
start_time = time.time()
|
||||
response = await async_client.post(
|
||||
"/api/v1/auth/login",
|
||||
json=login_data
|
||||
)
|
||||
end_time = time.time()
|
||||
return end_time - start_time, response.status_code
|
||||
|
||||
# 执行并发请求
|
||||
for _ in range(total_requests // concurrent_requests):
|
||||
tasks = [make_request() for _ in range(concurrent_requests)]
|
||||
results = await asyncio.gather(*tasks)
|
||||
|
||||
for response_time, status_code in results:
|
||||
assert status_code == 200
|
||||
response_times.append(response_time)
|
||||
|
||||
# 分析结果
|
||||
avg_response_time = mean(response_times)
|
||||
std_response_time = stdev(response_times)
|
||||
max_response_time = max(response_times)
|
||||
min_response_time = min(response_times)
|
||||
|
||||
# 性能断言
|
||||
assert avg_response_time < 0.1 # 平均响应时间小于100ms
|
||||
assert max_response_time < 0.5 # 最大响应时间小于500ms
|
||||
|
||||
print(f"\n性能测试结果:")
|
||||
print(f"平均响应时间: {avg_response_time*1000:.2f}ms")
|
||||
print(f"标准差: {std_response_time*1000:.2f}ms")
|
||||
print(f"最小响应时间: {min_response_time*1000:.2f}ms")
|
||||
print(f"最大响应时间: {max_response_time*1000:.2f}ms")
|
||||
```
|
||||
|
||||
## 3. 持续集成/持续部署 (CI/CD)
|
||||
|
||||
### 3.1 GitHub Actions配置
|
||||
```yaml
|
||||
# .github/workflows/ci.yml
|
||||
name: CI Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop]
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.8'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -r requirements/dev.txt
|
||||
|
||||
- name: Run linters
|
||||
run: |
|
||||
make lint
|
||||
make type-check
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: lint
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
env:
|
||||
MYSQL_ROOT_PASSWORD: testpassword
|
||||
MYSQL_DATABASE: testdb
|
||||
options: >-
|
||||
--health-cmd="mysqladmin ping"
|
||||
--health-interval=10s
|
||||
--health-timeout=5s
|
||||
--health-retries=5
|
||||
ports:
|
||||
- 3306:3306
|
||||
|
||||
redis:
|
||||
image: redis:7
|
||||
options: >-
|
||||
--health-cmd="redis-cli ping"
|
||||
--health-interval=10s
|
||||
--health-timeout=5s
|
||||
--health-retries=5
|
||||
ports:
|
||||
- 6379:6379
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.8'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -r requirements/dev.txt
|
||||
|
||||
- name: Run migrations
|
||||
env:
|
||||
DATABASE_URL: mysql+aiomysql://root:testpassword@localhost:3306/testdb
|
||||
run: |
|
||||
alembic upgrade head
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
DATABASE_URL: mysql+aiomysql://root:testpassword@localhost:3306/testdb
|
||||
REDIS_URL: redis://localhost:6379/0
|
||||
run: |
|
||||
pytest tests/ -v --cov=app --cov-report=xml
|
||||
|
||||
- name: Upload coverage
|
||||
uses: codecov/codecov-action@v3
|
||||
with:
|
||||
file: ./coverage.xml
|
||||
fail_ci_if_error: true
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Run security checks
|
||||
uses: pyupio/safety@v1
|
||||
with:
|
||||
api-key: ${{ secrets.SAFETY_API_KEY }}
|
||||
|
||||
- name: Run Bandit
|
||||
run: |
|
||||
pip install bandit
|
||||
bandit -r app/ -f json -o bandit-report.json
|
||||
|
||||
- name: Upload security report
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: security-reports
|
||||
path: bandit-report.json
|
||||
```
|
||||
|
||||
### 3.2 代码覆盖率配置
|
||||
```ini
|
||||
# .coveragerc
|
||||
[run]
|
||||
source = app
|
||||
omit =
|
||||
*/tests/*
|
||||
*/migrations/*
|
||||
*/__init__.py
|
||||
*/config/*
|
||||
|
||||
[report]
|
||||
precision = 2
|
||||
show_missing = True
|
||||
skip_covered = False
|
||||
|
||||
[html]
|
||||
directory = htmlcov
|
||||
|
||||
[xml]
|
||||
output = coverage.xml
|
||||
```
|
||||
|
||||
## 4. 代码审查流程
|
||||
|
||||
### 4.1 Pull Request模板
|
||||
```markdown
|
||||
<!-- .github/pull_request_template.md -->
|
||||
## 描述
|
||||
简要描述这个PR的目的和所做的更改。
|
||||
|
||||
## 更改类型
|
||||
- [ ] Bug修复
|
||||
- [ ] 新功能
|
||||
- [ ] 性能优化
|
||||
- [ ] 代码重构
|
||||
- [ ] 文档更新
|
||||
- [ ] 测试更新
|
||||
|
||||
## 检查清单
|
||||
- [ ] 代码符合项目的编码规范
|
||||
- [ ] 已添加/更新相关测试
|
||||
- [ ] 所有测试通过
|
||||
- [ ] 已更新相关文档
|
||||
- [ ] 代码已经过自我审查
|
||||
- [ ] 没有注释掉的代码
|
||||
- [ ] 没有console.log或print调试语句
|
||||
|
||||
## 测试说明
|
||||
描述如何测试这些更改。
|
||||
|
||||
## 相关Issue
|
||||
Closes #(issue号)
|
||||
|
||||
## 截图(如适用)
|
||||
如果有UI更改,请添加截图。
|
||||
```
|
||||
|
||||
### 4.2 代码审查标准
|
||||
```python
|
||||
# scripts/code_review_checklist.py
|
||||
"""代码审查检查工具"""
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Dict
|
||||
|
||||
class CodeReviewChecker(ast.NodeVisitor):
|
||||
"""代码审查自动检查器"""
|
||||
|
||||
def __init__(self):
|
||||
self.issues = []
|
||||
self.current_file = None
|
||||
|
||||
def check_file(self, file_path: Path) -> List[Dict[str, any]]:
|
||||
"""检查单个文件"""
|
||||
self.current_file = file_path
|
||||
self.issues = []
|
||||
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# 检查文件级别的问题
|
||||
self._check_file_issues(content)
|
||||
|
||||
# 解析AST并检查
|
||||
try:
|
||||
tree = ast.parse(content)
|
||||
self.visit(tree)
|
||||
except SyntaxError as e:
|
||||
self.issues.append({
|
||||
"type": "syntax_error",
|
||||
"line": e.lineno,
|
||||
"message": str(e)
|
||||
})
|
||||
|
||||
return self.issues
|
||||
|
||||
def _check_file_issues(self, content: str):
|
||||
"""检查文件级别的问题"""
|
||||
lines = content.split('\n')
|
||||
|
||||
for i, line in enumerate(lines, 1):
|
||||
# 检查行长度
|
||||
if len(line) > 88:
|
||||
self.issues.append({
|
||||
"type": "line_too_long",
|
||||
"line": i,
|
||||
"message": f"行长度 {len(line)} 超过88字符"
|
||||
})
|
||||
|
||||
# 检查TODO/FIXME
|
||||
if 'TODO' in line or 'FIXME' in line:
|
||||
self.issues.append({
|
||||
"type": "todo_found",
|
||||
"line": i,
|
||||
"message": "发现待处理的TODO/FIXME"
|
||||
})
|
||||
|
||||
# 检查print语句
|
||||
if 'print(' in line and not line.strip().startswith('#'):
|
||||
self.issues.append({
|
||||
"type": "print_statement",
|
||||
"line": i,
|
||||
"message": "使用了print语句,应使用日志"
|
||||
})
|
||||
|
||||
def visit_FunctionDef(self, node):
|
||||
"""检查函数定义"""
|
||||
# 检查函数复杂度
|
||||
complexity = self._calculate_complexity(node)
|
||||
if complexity > 10:
|
||||
self.issues.append({
|
||||
"type": "high_complexity",
|
||||
"line": node.lineno,
|
||||
"message": f"函数 {node.name} 复杂度 {complexity} 过高"
|
||||
})
|
||||
|
||||
# 检查是否有文档字符串
|
||||
if not ast.get_docstring(node):
|
||||
self.issues.append({
|
||||
"type": "missing_docstring",
|
||||
"line": node.lineno,
|
||||
"message": f"函数 {node.name} 缺少文档字符串"
|
||||
})
|
||||
|
||||
self.generic_visit(node)
|
||||
|
||||
def _calculate_complexity(self, node) -> int:
|
||||
"""计算圈复杂度"""
|
||||
complexity = 1
|
||||
for child in ast.walk(node):
|
||||
if isinstance(child, (ast.If, ast.While, ast.For)):
|
||||
complexity += 1
|
||||
elif isinstance(child, ast.ExceptHandler):
|
||||
complexity += 1
|
||||
return complexity
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
checker = CodeReviewChecker()
|
||||
|
||||
# 检查所有Python文件
|
||||
app_dir = Path("app")
|
||||
all_issues = []
|
||||
|
||||
for py_file in app_dir.rglob("*.py"):
|
||||
issues = checker.check_file(py_file)
|
||||
if issues:
|
||||
all_issues.append({
|
||||
"file": str(py_file),
|
||||
"issues": issues
|
||||
})
|
||||
|
||||
# 输出结果
|
||||
if all_issues:
|
||||
print("代码审查发现以下问题:")
|
||||
for file_issues in all_issues:
|
||||
print(f"\n文件: {file_issues['file']}")
|
||||
for issue in file_issues['issues']:
|
||||
print(f" 行 {issue['line']}: [{issue['type']}] {issue['message']}")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("代码审查通过!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
## 5. 安全保证
|
||||
|
||||
### 5.1 安全扫描配置
|
||||
```yaml
|
||||
# .github/workflows/security.yml
|
||||
name: Security Scan
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *' # 每天运行
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
scan-type: 'fs'
|
||||
scan-ref: '.'
|
||||
format: 'sarif'
|
||||
output: 'trivy-results.sarif'
|
||||
|
||||
- name: Upload Trivy scan results
|
||||
uses: github/codeql-action/upload-sarif@v2
|
||||
with:
|
||||
sarif_file: 'trivy-results.sarif'
|
||||
|
||||
- name: OWASP Dependency Check
|
||||
uses: dependency-check/Dependency-Check_Action@main
|
||||
with:
|
||||
project: 'kaopeilian-backend'
|
||||
path: '.'
|
||||
format: 'ALL'
|
||||
```
|
||||
|
||||
### 5.2 安全最佳实践检查
|
||||
```python
|
||||
# app/core/security_checks.py
|
||||
"""运行时安全检查"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import List, Dict
|
||||
from pathlib import Path
|
||||
|
||||
class SecurityChecker:
|
||||
"""安全检查器"""
|
||||
|
||||
@staticmethod
|
||||
def check_env_variables() -> List[str]:
|
||||
"""检查环境变量安全性"""
|
||||
issues = []
|
||||
|
||||
# 检查敏感配置
|
||||
sensitive_vars = [
|
||||
'SECRET_KEY',
|
||||
'DATABASE_URL',
|
||||
'COZE_API_TOKEN',
|
||||
'DIFY_API_KEY'
|
||||
]
|
||||
|
||||
for var in sensitive_vars:
|
||||
value = os.getenv(var)
|
||||
if not value:
|
||||
issues.append(f"缺少必要的环境变量: {var}")
|
||||
elif var == 'SECRET_KEY' and len(value) < 32:
|
||||
issues.append("SECRET_KEY 长度不足32字符")
|
||||
|
||||
return issues
|
||||
|
||||
@staticmethod
|
||||
def check_sql_injection_patterns(query: str) -> bool:
|
||||
"""检查SQL注入模式"""
|
||||
dangerous_patterns = [
|
||||
r';\s*DROP\s+TABLE',
|
||||
r';\s*DELETE\s+FROM',
|
||||
r'UNION\s+SELECT',
|
||||
r'OR\s+1\s*=\s*1',
|
||||
r'--\s*$'
|
||||
]
|
||||
|
||||
for pattern in dangerous_patterns:
|
||||
if re.search(pattern, query, re.IGNORECASE):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def check_file_upload(filename: str, content: bytes) -> Dict[str, any]:
|
||||
"""检查文件上传安全性"""
|
||||
issues = []
|
||||
|
||||
# 检查文件扩展名
|
||||
allowed_extensions = {'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.png', '.jpg', '.jpeg'}
|
||||
ext = Path(filename).suffix.lower()
|
||||
if ext not in allowed_extensions:
|
||||
issues.append(f"不允许的文件类型: {ext}")
|
||||
|
||||
# 检查文件大小
|
||||
max_size = 10 * 1024 * 1024 # 10MB
|
||||
if len(content) > max_size:
|
||||
issues.append(f"文件大小超过限制: {len(content)/1024/1024:.2f}MB > 10MB")
|
||||
|
||||
# 检查文件内容魔术字节
|
||||
magic_bytes = {
|
||||
b'\x89PNG': '.png',
|
||||
b'\xFF\xD8\xFF': '.jpg',
|
||||
b'%PDF': '.pdf'
|
||||
}
|
||||
|
||||
file_type_valid = False
|
||||
for magic, expected_ext in magic_bytes.items():
|
||||
if content.startswith(magic) and ext == expected_ext:
|
||||
file_type_valid = True
|
||||
break
|
||||
|
||||
if not file_type_valid and ext in {'.png', '.jpg', '.pdf'}:
|
||||
issues.append("文件内容与扩展名不匹配")
|
||||
|
||||
return {
|
||||
"valid": len(issues) == 0,
|
||||
"issues": issues
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 监控与告警
|
||||
|
||||
### 6.1 健康检查端点
|
||||
```python
|
||||
# app/api/v1/health.py
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.core.deps import get_db
|
||||
from app.services.ai.coze.client import CozeClient
|
||||
from app.services.ai.dify.client import DifyClient
|
||||
import redis.asyncio as redis
|
||||
from datetime import datetime
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
"""基础健康检查"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check(
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""详细健康检查"""
|
||||
health_status = {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"checks": {}
|
||||
}
|
||||
|
||||
# 检查数据库
|
||||
try:
|
||||
await db.execute("SELECT 1")
|
||||
health_status["checks"]["database"] = {
|
||||
"status": "up",
|
||||
"response_time_ms": 5
|
||||
}
|
||||
except Exception as e:
|
||||
health_status["status"] = "unhealthy"
|
||||
health_status["checks"]["database"] = {
|
||||
"status": "down",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
# 检查Redis
|
||||
try:
|
||||
r = redis.from_url("redis://localhost:6379")
|
||||
await r.ping()
|
||||
health_status["checks"]["redis"] = {
|
||||
"status": "up",
|
||||
"response_time_ms": 2
|
||||
}
|
||||
except Exception as e:
|
||||
health_status["status"] = "degraded"
|
||||
health_status["checks"]["redis"] = {
|
||||
"status": "down",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
# 检查Coze连接
|
||||
try:
|
||||
coze = CozeClient()
|
||||
# 执行简单的API调用测试
|
||||
health_status["checks"]["coze"] = {
|
||||
"status": "up",
|
||||
"response_time_ms": 50
|
||||
}
|
||||
except Exception as e:
|
||||
health_status["status"] = "degraded"
|
||||
health_status["checks"]["coze"] = {
|
||||
"status": "down",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
return health_status
|
||||
```
|
||||
|
||||
### 6.2 性能监控指标
|
||||
```python
|
||||
# app/core/metrics.py
|
||||
from prometheus_client import Counter, Histogram, Gauge, generate_latest
|
||||
from functools import wraps
|
||||
import time
|
||||
|
||||
# 定义指标
|
||||
http_requests_total = Counter(
|
||||
'http_requests_total',
|
||||
'Total HTTP requests',
|
||||
['method', 'endpoint', 'status']
|
||||
)
|
||||
|
||||
http_request_duration_seconds = Histogram(
|
||||
'http_request_duration_seconds',
|
||||
'HTTP request duration',
|
||||
['method', 'endpoint']
|
||||
)
|
||||
|
||||
active_connections = Gauge(
|
||||
'active_connections',
|
||||
'Number of active connections'
|
||||
)
|
||||
|
||||
ai_api_calls_total = Counter(
|
||||
'ai_api_calls_total',
|
||||
'Total AI API calls',
|
||||
['platform', 'operation', 'status']
|
||||
)
|
||||
|
||||
def track_request_metrics(endpoint: str):
|
||||
"""请求指标追踪装饰器"""
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
method = kwargs.get('request', args[0]).method
|
||||
|
||||
try:
|
||||
response = await func(*args, **kwargs)
|
||||
status = response.status_code
|
||||
http_requests_total.labels(
|
||||
method=method,
|
||||
endpoint=endpoint,
|
||||
status=status
|
||||
).inc()
|
||||
return response
|
||||
finally:
|
||||
duration = time.time() - start_time
|
||||
http_request_duration_seconds.labels(
|
||||
method=method,
|
||||
endpoint=endpoint
|
||||
).observe(duration)
|
||||
|
||||
return wrapper
|
||||
return decorator
|
||||
```
|
||||
|
||||
## 7. 发布管理
|
||||
|
||||
### 7.1 版本控制策略
|
||||
```bash
|
||||
# 版本号格式:MAJOR.MINOR.PATCH
|
||||
# MAJOR: 不兼容的API更改
|
||||
# MINOR: 向后兼容的功能添加
|
||||
# PATCH: 向后兼容的错误修复
|
||||
|
||||
# 自动版本号管理脚本
|
||||
#!/bin/bash
|
||||
# scripts/bump_version.sh
|
||||
|
||||
CURRENT_VERSION=$(cat VERSION)
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$CURRENT_VERSION"
|
||||
|
||||
case $1 in
|
||||
major)
|
||||
NEW_VERSION="$((VERSION_PARTS[0] + 1)).0.0"
|
||||
;;
|
||||
minor)
|
||||
NEW_VERSION="${VERSION_PARTS[0]}.$((VERSION_PARTS[1] + 1)).0"
|
||||
;;
|
||||
patch)
|
||||
NEW_VERSION="${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.$((VERSION_PARTS[2] + 1))"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {major|minor|patch}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo $NEW_VERSION > VERSION
|
||||
echo "Version bumped from $CURRENT_VERSION to $NEW_VERSION"
|
||||
```
|
||||
|
||||
### 7.2 发布检查清单
|
||||
```markdown
|
||||
## 发布前检查清单
|
||||
|
||||
### 代码质量
|
||||
- [ ] 所有测试通过
|
||||
- [ ] 代码覆盖率达标(>80%)
|
||||
- [ ] 无安全漏洞警告
|
||||
- [ ] 性能测试通过
|
||||
|
||||
### 文档
|
||||
- [ ] API文档已更新
|
||||
- [ ] CHANGELOG已更新
|
||||
- [ ] README已更新
|
||||
- [ ] 部署文档已更新
|
||||
|
||||
### 配置
|
||||
- [ ] 环境变量已配置
|
||||
- [ ] 数据库迁移已准备
|
||||
- [ ] 依赖版本已锁定
|
||||
|
||||
### 回滚计划
|
||||
- [ ] 数据库备份已完成
|
||||
- [ ] 回滚脚本已准备
|
||||
- [ ] 回滚流程已测试
|
||||
|
||||
### 通知
|
||||
- [ ] 相关团队已通知
|
||||
- [ ] 维护窗口已安排
|
||||
- [ ] 监控告警已配置
|
||||
```
|
||||
|
||||
123
docs/规划/后端开发拆分策略/配置一致性检查清单.md
Normal file
123
docs/规划/后端开发拆分策略/配置一致性检查清单.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# 配置一致性检查清单
|
||||
|
||||
## 📋 概述
|
||||
本文档记录了项目中各个组件之间必须保持一致的配置项,确保系统正常运行。
|
||||
|
||||
## 🔧 数据库配置一致性
|
||||
|
||||
### MySQL连接配置
|
||||
| 组件 | 配置文件 | 配置项 | 当前值 |
|
||||
|------|----------|--------|--------|
|
||||
| Docker Compose | `../../docker-compose.yml` | `MYSQL_ROOT_PASSWORD` | `root` |
|
||||
| 后端默认配置 | `../../kaopeilian-backend/app/config/settings.py` | `DATABASE_URL` | `mysql+aiomysql://root:root@localhost:3306/kaopeilian` |
|
||||
| 启动脚本 | `../../kaopeilian-backend/start_mysql.py` | `DATABASE_URL` 环境变量 | `mysql+aiomysql://root:root@localhost:3306/kaopeilian` |
|
||||
|
||||
**⚠️ 重要**:所有数据库连接字符串中的用户名、密码、主机、端口必须完全一致。
|
||||
|
||||
### Redis连接配置
|
||||
| 组件 | 配置文件 | 配置项 | 当前值 |
|
||||
|------|----------|--------|--------|
|
||||
| Docker Compose | `../../docker-compose.yml` | Redis端口 | `6379` |
|
||||
| 后端配置 | `../../kaopeilian-backend/app/config/settings.py` | `REDIS_URL` | `redis://localhost:6379/0` |
|
||||
|
||||
## 🌐 网络配置一致性
|
||||
|
||||
### 端口配置
|
||||
| 服务 | 组件 | 配置位置 | 端口 |
|
||||
|------|------|----------|------|
|
||||
| 前端开发服务器 | Vue3 + Vite | `../../kaopeilian-frontend/vite.config.ts` | `3001` |
|
||||
| 后端API服务器 | FastAPI | `../../kaopeilian-backend/start_mysql.py` | `8000` |
|
||||
| MySQL数据库 | Docker | `../../docker-compose.yml` | `3306` |
|
||||
| Redis缓存 | Docker | `../../docker-compose.yml` | `6379` |
|
||||
|
||||
### CORS配置
|
||||
| 组件 | 配置文件 | 配置项 | 允许的源 |
|
||||
|------|----------|--------|----------|
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `BACKEND_CORS_ORIGINS` | `["http://localhost:3000", "http://localhost:3001", "http://localhost:5173"]` |
|
||||
|
||||
**⚠️ 重要**:前端开发服务器的端口必须在后端CORS配置中明确允许。
|
||||
|
||||
## 🔐 认证配置一致性
|
||||
|
||||
### JWT配置
|
||||
| 组件 | 配置文件 | 配置项 | 当前值 |
|
||||
|------|----------|--------|--------|
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `SECRET_KEY` | 环境变量或默认值 |
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `ALGORITHM` | `HS256` |
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `ACCESS_TOKEN_EXPIRE_MINUTES` | `30` |
|
||||
|
||||
### 认证存储键名
|
||||
| 组件 | 存储位置 | 键名 | 用途 |
|
||||
|------|----------|------|------|
|
||||
| 前端 | localStorage | `access_token` | 访问令牌 |
|
||||
| 前端 | localStorage | `refresh_token` | 刷新令牌 |
|
||||
| 前端 | localStorage | `current_user` | 当前用户信息 |
|
||||
|
||||
**⚠️ 重要**:前端的authManager和所有组件必须使用相同的localStorage键名。
|
||||
|
||||
## 📡 API配置一致性
|
||||
|
||||
### 请求格式
|
||||
| API端点 | 前端发送格式 | 后端接收格式 | Content-Type |
|
||||
|---------|-------------|-------------|--------------|
|
||||
| `/api/v1/auth/login` | JSON | Pydantic模型 | `application/json` |
|
||||
| `/api/v1/auth/register` | JSON | Pydantic模型 | `application/json` |
|
||||
|
||||
### API基础路径
|
||||
| 组件 | 配置文件 | 配置项 | 当前值 |
|
||||
|------|----------|--------|--------|
|
||||
| 前端 | `../../kaopeilian-frontend/src/api/config.ts` | `baseURL` | `http://localhost:8000` |
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `API_V1_STR` | `/api/v1` |
|
||||
|
||||
## 🏗️ 环境配置一致性
|
||||
|
||||
### 开发环境
|
||||
| 组件 | 配置文件 | 环境标识 | 当前值 |
|
||||
|------|----------|----------|--------|
|
||||
| 前端 | `../../kaopeilian-frontend/package.json` | `NODE_ENV` | `development` |
|
||||
| 后端 | `../../kaopeilian-backend/app/config/settings.py` | `ENVIRONMENT` | `development` |
|
||||
|
||||
## ✅ 配置检查脚本
|
||||
|
||||
### 自动检查命令
|
||||
```bash
|
||||
# 在项目根目录执行
|
||||
cd ../../
|
||||
./check-config.sh
|
||||
```
|
||||
|
||||
### 手动检查清单
|
||||
- [ ] Docker服务正常启动 (`docker-compose ps`)
|
||||
- [ ] 数据库连接成功 (后端日志无连接错误)
|
||||
- [ ] 前端可以访问后端API (无CORS错误)
|
||||
- [ ] 认证流程完整工作 (登录成功并跳转)
|
||||
- [ ] 权限控制正常 (不同角色访问不同页面)
|
||||
|
||||
## 🚨 常见配置不一致问题
|
||||
|
||||
### 1. 数据库密码不匹配
|
||||
**症状**:后端启动时报"Access denied"错误
|
||||
**解决**:检查`docker-compose.yml`的`MYSQL_ROOT_PASSWORD`与`settings.py`的`DATABASE_URL`密码是否一致
|
||||
|
||||
### 2. CORS配置缺失
|
||||
**症状**:前端控制台报CORS错误
|
||||
**解决**:确保前端运行端口已添加到后端`BACKEND_CORS_ORIGINS`列表
|
||||
|
||||
### 3. API格式不匹配
|
||||
**症状**:前端请求返回400或422错误
|
||||
**解决**:检查前端发送的Content-Type和数据格式是否与后端Pydantic模型匹配
|
||||
|
||||
### 4. 认证状态不同步
|
||||
**症状**:登录成功但路由守卫仍然拦截
|
||||
**解决**:确保前端使用统一的authManager,localStorage键名一致
|
||||
|
||||
## 📝 更新记录
|
||||
|
||||
| 日期 | 更新内容 | 更新人 |
|
||||
|------|----------|--------|
|
||||
| 2025-09-20 | 初始创建配置一致性检查清单 | AI Assistant |
|
||||
| 2025-09-20 | 添加认证授权模块配置项 | AI Assistant |
|
||||
|
||||
---
|
||||
|
||||
**注意**:每次添加新的配置项或修改现有配置时,都必须更新此文档,确保团队成员了解配置要求。
|
||||
176
docs/规划/后端开发拆分策略/配置管理使用说明.md
Normal file
176
docs/规划/后端开发拆分策略/配置管理使用说明.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# 配置管理使用说明
|
||||
|
||||
## 📋 概述
|
||||
|
||||
本文档说明如何使用配置管理工具来确保系统配置一致性,避免常见的配置错误。
|
||||
|
||||
## 🛠️ 工具列表
|
||||
|
||||
### 1. 配置一致性检查清单
|
||||
**文件**: `配置一致性检查清单.md`
|
||||
**用途**: 详细记录所有需要保持一致的配置项
|
||||
**使用场景**:
|
||||
- 新开发人员入职时的配置参考
|
||||
- 系统部署前的配置核对
|
||||
- 故障排查时的配置检查
|
||||
|
||||
### 2. 自动配置检查脚本
|
||||
**文件**: `../../../check-config.sh`
|
||||
**用途**: 自动检查系统配置状态
|
||||
**使用方法**:
|
||||
```bash
|
||||
# 在项目根目录执行
|
||||
./check-config.sh
|
||||
```
|
||||
|
||||
**检查内容**:
|
||||
- ✅ Docker服务状态
|
||||
- ✅ 端口占用情况
|
||||
- ✅ 服务健康状态
|
||||
- ✅ 配置文件存在性
|
||||
- ✅ 认证功能测试
|
||||
- ✅ CORS配置验证
|
||||
|
||||
### 3. 通用基础提示词
|
||||
**文件**: `子agent/00-通用基础/base_prompt.md`
|
||||
**用途**: 为所有子agent提供统一的开发规范和调试方法
|
||||
**核心内容**:
|
||||
- 系统化问题定位策略
|
||||
- 配置一致性检查方法
|
||||
- 常见错误处理模式
|
||||
- 开发最佳实践
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 第一次使用
|
||||
1. **阅读配置清单**:
|
||||
```bash
|
||||
cat "配置一致性检查清单.md"
|
||||
```
|
||||
|
||||
2. **运行配置检查**:
|
||||
```bash
|
||||
cd ../../../
|
||||
./check-config.sh
|
||||
```
|
||||
|
||||
3. **根据结果修复问题**:
|
||||
- 如果有失败项,按照建议进行修复
|
||||
- 重新运行检查直到所有项都通过
|
||||
|
||||
### 日常开发使用
|
||||
|
||||
#### 开发前检查
|
||||
```bash
|
||||
# 快速检查系统状态
|
||||
cd ../../../
|
||||
./check-config.sh
|
||||
|
||||
# 如果有问题,启动必要服务
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
#### 遇到问题时
|
||||
1. **先运行配置检查**:
|
||||
```bash
|
||||
cd ../../../
|
||||
./check-config.sh
|
||||
```
|
||||
|
||||
2. **对照配置清单**:
|
||||
- 检查数据库连接配置
|
||||
- 验证CORS域名设置
|
||||
- 确认API格式匹配
|
||||
|
||||
3. **查看通用提示词**:
|
||||
- 按照分层验证法定位问题
|
||||
- 使用错误分类处理方法
|
||||
|
||||
## 📊 配置检查结果解读
|
||||
|
||||
### 正常输出示例
|
||||
```
|
||||
🎉 所有检查都通过了!系统配置正常。
|
||||
通过: 15
|
||||
失败: 0
|
||||
```
|
||||
|
||||
### 异常输出示例
|
||||
```
|
||||
⚠️ 发现 3 个问题,请检查配置。
|
||||
通过: 12
|
||||
失败: 3
|
||||
|
||||
💡 解决建议:
|
||||
1. 确保Docker服务已启动: docker-compose up -d
|
||||
2. 检查端口是否被占用或服务未启动
|
||||
3. 参考 '配置一致性检查清单.md' 核对配置
|
||||
```
|
||||
|
||||
## 🔧 常见问题解决
|
||||
|
||||
### 1. Docker服务未运行
|
||||
**症状**: `❌ Docker 服务 mysql 未运行`
|
||||
**解决**:
|
||||
```bash
|
||||
cd ../../../
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### 2. 端口被占用
|
||||
**症状**: `❌ 端口 8000 未占用`
|
||||
**解决**: 检查对应服务是否启动,或端口是否被其他程序占用
|
||||
|
||||
### 3. 认证功能失败
|
||||
**症状**: `❌ 检查登录API 失败`
|
||||
**解决**:
|
||||
1. 检查后端服务是否正常运行
|
||||
2. 验证数据库连接配置
|
||||
3. 确认测试用户是否存在
|
||||
|
||||
### 4. CORS配置问题
|
||||
**症状**: `❌ 检查CORS预检请求 失败`
|
||||
**解决**:
|
||||
1. 检查后端CORS配置中是否包含前端端口
|
||||
2. 确认前端运行在正确的端口上
|
||||
|
||||
## 📝 配置维护流程
|
||||
|
||||
### 添加新配置项
|
||||
1. 在`配置一致性检查清单.md`中记录新配置
|
||||
2. 如需要,在`../../../check-config.sh`中添加检查逻辑
|
||||
3. 更新`子agent/00-通用基础/base_prompt.md`中的相关说明
|
||||
|
||||
### 修改现有配置
|
||||
1. 同时更新所有相关组件的配置
|
||||
2. 运行配置检查脚本验证
|
||||
3. 更新配置清单文档
|
||||
|
||||
### 部署新环境
|
||||
1. 复制配置文件模板
|
||||
2. 根据环境修改配置值
|
||||
3. 运行配置检查确保一致性
|
||||
4. 测试核心功能正常工作
|
||||
|
||||
## 🎯 最佳实践
|
||||
|
||||
### 开发团队协作
|
||||
1. **统一工具**: 所有团队成员都使用相同的配置检查工具
|
||||
2. **定期检查**: 每天开始工作前运行一次配置检查
|
||||
3. **问题共享**: 遇到新的配置问题时,及时更新文档和工具
|
||||
|
||||
### 配置管理原则
|
||||
1. **版本控制**: 所有配置文件都纳入版本控制
|
||||
2. **环境隔离**: 不同环境使用不同的配置文件
|
||||
3. **敏感信息**: 密码等敏感信息使用环境变量管理
|
||||
4. **文档同步**: 配置变更时同步更新文档
|
||||
|
||||
### 故障处理流程
|
||||
1. **快速定位**: 使用配置检查脚本快速发现问题
|
||||
2. **系统排查**: 按照分层验证法逐层检查
|
||||
3. **根本解决**: 不仅修复症状,还要解决根本原因
|
||||
4. **经验沉淀**: 将解决方案更新到文档和工具中
|
||||
|
||||
---
|
||||
|
||||
**记住**: 配置一致性是分布式系统稳定运行的基础,投入时间维护配置管理工具能够大大提高开发效率和系统可靠性!
|
||||
91
docs/规划/后端开发拆分策略/项目脚手架创建完成.md
Normal file
91
docs/规划/后端开发拆分策略/项目脚手架创建完成.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# 项目脚手架创建完成 ✅
|
||||
|
||||
## 创建时间
|
||||
2025-01-XX
|
||||
|
||||
## 项目位置
|
||||
`/Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend/`
|
||||
|
||||
## 已创建的内容
|
||||
|
||||
### 1. 目录结构 ✅
|
||||
完全按照[项目脚手架结构.md](./项目脚手架结构.md)中的设计创建了所有必要的目录:
|
||||
- `app/` - 应用主目录
|
||||
- `tests/` - 测试目录
|
||||
- `migrations/` - 数据库迁移目录
|
||||
- `requirements/` - 依赖管理目录
|
||||
- `docker/` - Docker配置目录
|
||||
- `docs/` - 文档目录
|
||||
- `scripts/` - 脚本工具目录
|
||||
- `logs/` - 日志目录
|
||||
- `uploads/` - 上传文件目录
|
||||
|
||||
### 2. 核心代码文件 ✅
|
||||
- `app/main.py` - FastAPI应用入口
|
||||
- `app/config/settings.py` - 系统配置管理
|
||||
- `app/config/database.py` - 数据库配置
|
||||
- `app/models/base.py` - 基础模型类
|
||||
- `app/schemas/base.py` - 基础Schema类
|
||||
- `app/core/exceptions.py` - 统一异常处理
|
||||
- `app/core/logger.py` - 日志配置
|
||||
- `app/core/middleware.py` - 中间件定义
|
||||
- `app/core/events.py` - 生命周期事件
|
||||
- `app/api/v1/__init__.py` - API路由初始化
|
||||
|
||||
### 3. 配置文件 ✅
|
||||
- `.env.example` - 环境变量示例
|
||||
- `requirements/base.txt` - 基础依赖
|
||||
- `requirements/dev.txt` - 开发依赖
|
||||
- `requirements/prod.txt` - 生产依赖
|
||||
- `Makefile` - 开发命令集合
|
||||
- `setup.cfg` - 代码质量检查配置
|
||||
- `pyproject.toml` - Python项目配置
|
||||
- `.gitignore` - Git忽略文件
|
||||
|
||||
### 4. Docker相关 ✅
|
||||
- `Dockerfile` - Docker镜像构建文件
|
||||
- `docker-compose.yml` - Docker Compose配置
|
||||
|
||||
### 5. 文档和脚本 ✅
|
||||
- `README.md` - 项目说明文档
|
||||
- `scripts/init_project.sh` - 项目初始化脚本
|
||||
|
||||
## 下一步操作
|
||||
|
||||
各个子Agent现在可以:
|
||||
|
||||
1. **克隆或进入项目目录**
|
||||
```bash
|
||||
cd /Users/nongjun/Desktop/Ai公司/本地开发与测试/kaopeilian-backend
|
||||
```
|
||||
|
||||
2. **运行初始化脚本**
|
||||
```bash
|
||||
./scripts/init_project.sh
|
||||
```
|
||||
|
||||
3. **根据分工开发对应模块**
|
||||
- 查看[模块分工指南](./模块分工指南.md)确认负责的模块
|
||||
- 在对应的目录下创建模块代码
|
||||
- 遵循[开发规范文档](./开发规范文档.md)
|
||||
|
||||
4. **使用统一的基础代码**
|
||||
- 继承 `app/models/base.py` 中的基类
|
||||
- 使用 `app/schemas/base.py` 中的通用模式
|
||||
- 复用 `app/core/` 中的工具函数
|
||||
|
||||
## 重要提示
|
||||
|
||||
- ⚠️ 所有Agent必须遵循统一的代码规范
|
||||
- ⚠️ 使用提供的基础类和工具,避免重复造轮子
|
||||
- ⚠️ 定期同步代码,避免冲突
|
||||
- ⚠️ 编写充分的测试用例
|
||||
- ⚠️ 及时更新文档
|
||||
|
||||
## 项目状态
|
||||
|
||||
✅ **第一阶段已完成**:统一基础架构已建立
|
||||
- ✅ 创建统一的项目脚手架
|
||||
- ✅ 建立统一的开发规范文档
|
||||
|
||||
现在可以进入**第二阶段**:模块化分配开发!
|
||||
229
docs/规划/后端开发拆分策略/项目脚手架结构.md
Normal file
229
docs/规划/后端开发拆分策略/项目脚手架结构.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# 考培练系统后端项目脚手架结构
|
||||
|
||||
## 完整的项目目录结构
|
||||
|
||||
```
|
||||
kaopeilian-backend/
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py # FastAPI 应用入口
|
||||
│ ├── config/ # 统一配置管理
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── settings.py # 系统配置
|
||||
│ │ ├── database.py # 数据库配置
|
||||
│ │ ├── coze_config.py # Coze平台配置
|
||||
│ │ └── dify_config.py # Dify平台配置
|
||||
│ ├── core/ # 核心公共模块
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── dependencies.py # 依赖注入
|
||||
│ │ ├── security.py # 认证授权
|
||||
│ │ ├── exceptions.py # 统一异常处理
|
||||
│ │ ├── middleware.py # 中间件
|
||||
│ │ └── logger.py # 日志配置
|
||||
│ ├── models/ # 数据库模型(统一)
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── base.py # 基础模型类
|
||||
│ │ ├── user.py # 用户相关模型
|
||||
│ │ ├── course.py # 课程相关模型
|
||||
│ │ ├── exam.py # 考试相关模型
|
||||
│ │ ├── training.py # 陪练相关模型
|
||||
│ │ └── analytics.py # 分析相关模型
|
||||
│ ├── schemas/ # Pydantic 模式(统一)
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── base.py # 基础响应模式
|
||||
│ │ ├── user.py # 用户相关模式
|
||||
│ │ ├── course.py # 课程相关模式
|
||||
│ │ ├── exam.py # 考试相关模式
|
||||
│ │ ├── training.py # 陪练相关模式
|
||||
│ │ └── analytics.py # 分析相关模式
|
||||
│ ├── services/ # 业务逻辑服务层
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── base_service.py # 基础服务类
|
||||
│ │ ├── user_service.py # 用户业务逻辑
|
||||
│ │ ├── course_service.py # 课程业务逻辑
|
||||
│ │ ├── exam_service.py # 考试业务逻辑
|
||||
│ │ ├── training_service.py # 陪练业务逻辑
|
||||
│ │ ├── analytics_service.py # 分析业务逻辑
|
||||
│ │ ├── ai/ # AI平台集成服务
|
||||
│ │ │ ├── __init__.py
|
||||
│ │ │ ├── base_ai_service.py # AI服务基类
|
||||
│ │ │ ├── coze/ # Coze API 集成
|
||||
│ │ │ │ ├── __init__.py
|
||||
│ │ │ │ ├── client.py # Coze客户端封装
|
||||
│ │ │ │ ├── training.py # AI陪练功能
|
||||
│ │ │ │ └── chat.py # 课程对话功能
|
||||
│ │ │ └── dify/ # Dify API 集成
|
||||
│ │ │ ├── __init__.py
|
||||
│ │ │ ├── client.py # Dify客户端封装
|
||||
│ │ │ ├── exam.py # 动态考试功能
|
||||
│ │ │ ├── assessment.py # 能力评估功能
|
||||
│ │ │ └── recommend.py # 课程推荐功能
|
||||
│ │ └── external/ # 外部服务集成
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── sms_service.py # 短信服务
|
||||
│ │ └── badge_service.py # 智能工牌API
|
||||
│ └── api/ # API 路由(按模块分离)
|
||||
│ ├── __init__.py
|
||||
│ ├── deps.py # 路由依赖
|
||||
│ └── v1/ # API v1版本
|
||||
│ ├── __init__.py
|
||||
│ ├── auth.py # 认证相关
|
||||
│ ├── users.py # 用户管理
|
||||
│ ├── courses.py # 课程管理
|
||||
│ ├── exams.py # 考试模块
|
||||
│ ├── training.py # 陪练模块
|
||||
│ ├── analytics.py # 数据分析
|
||||
│ ├── admin.py # 系统管理
|
||||
│ └── websocket.py # WebSocket支持
|
||||
├── migrations/ # 数据库迁移
|
||||
│ └── alembic/
|
||||
│ ├── alembic.ini
|
||||
│ └── versions/
|
||||
├── tests/ # 测试代码
|
||||
│ ├── __init__.py
|
||||
│ ├── conftest.py # 测试配置
|
||||
│ ├── unit/ # 单元测试
|
||||
│ ├── integration/ # 集成测试
|
||||
│ └── e2e/ # 端到端测试
|
||||
├── scripts/ # 脚本工具
|
||||
│ ├── init_db.py # 初始化数据库
|
||||
│ ├── seed_data.py # 种子数据
|
||||
│ └── generate_docs.py # 生成文档
|
||||
├── docs/ # 项目文档
|
||||
│ ├── api/ # API文档
|
||||
│ ├── development/ # 开发文档
|
||||
│ └── deployment/ # 部署文档
|
||||
├── requirements/ # 依赖管理
|
||||
│ ├── base.txt # 基础依赖
|
||||
│ ├── dev.txt # 开发依赖
|
||||
│ └── prod.txt # 生产依赖
|
||||
├── docker/ # Docker相关
|
||||
│ ├── Dockerfile
|
||||
│ ├── Dockerfile.dev # 开发环境
|
||||
│ └── nginx/ # Nginx配置
|
||||
├── .env.example # 环境变量示例
|
||||
├── .gitignore
|
||||
├── docker-compose.yml # 本地开发
|
||||
├── docker-compose.prod.yml # 生产环境
|
||||
├── Makefile # 快捷命令
|
||||
├── README.md # 项目说明
|
||||
└── pyproject.toml # Python项目配置
|
||||
```
|
||||
|
||||
## AI平台集成架构
|
||||
|
||||
### Coze平台集成(用于AI陪练和课程对话)
|
||||
```python
|
||||
# app/services/ai/coze/client.py
|
||||
from cozepy import Coze, TokenAuth
|
||||
from app.config.coze_config import settings
|
||||
|
||||
class CozeClient:
|
||||
"""Coze平台客户端封装"""
|
||||
def __init__(self):
|
||||
self.client = Coze(
|
||||
auth=TokenAuth(settings.COZE_API_TOKEN),
|
||||
base_url=settings.COZE_API_BASE
|
||||
)
|
||||
|
||||
async def create_conversation(self, bot_id: str):
|
||||
"""创建会话"""
|
||||
pass
|
||||
|
||||
async def stream_chat(self, bot_id: str, conversation_id: str, message: str):
|
||||
"""流式对话"""
|
||||
pass
|
||||
```
|
||||
|
||||
### Dify平台集成(用于动态考试和能力评估)
|
||||
```python
|
||||
# app/services/ai/dify/client.py
|
||||
import httpx
|
||||
from app.config.dify_config import settings
|
||||
|
||||
class DifyClient:
|
||||
"""Dify平台客户端封装"""
|
||||
def __init__(self):
|
||||
self.base_url = settings.DIFY_API_BASE
|
||||
self.api_key = settings.DIFY_API_KEY
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
headers={"Authorization": f"Bearer {self.api_key}"}
|
||||
)
|
||||
|
||||
async def run_workflow(self, workflow_id: str, inputs: dict):
|
||||
"""运行Dify工作流"""
|
||||
pass
|
||||
|
||||
async def query_knowledge_base(self, kb_id: str, query: str):
|
||||
"""查询知识库"""
|
||||
pass
|
||||
```
|
||||
|
||||
## 配置文件示例
|
||||
|
||||
### Coze配置(app/config/coze_config.py)
|
||||
```python
|
||||
from pydantic import BaseSettings
|
||||
|
||||
class CozeSettings(BaseSettings):
|
||||
COZE_API_BASE: str = "https://api.coze.cn"
|
||||
COZE_WORKSPACE_ID: str
|
||||
COZE_API_TOKEN: str
|
||||
|
||||
# Bot IDs
|
||||
COZE_TRAINING_BOT_ID: str # AI陪练智能体
|
||||
COZE_CHAT_BOT_ID: str # 课程对话智能体
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
```
|
||||
|
||||
### Dify配置(app/config/dify_config.py)
|
||||
```python
|
||||
from pydantic import BaseSettings
|
||||
|
||||
class DifySettings(BaseSettings):
|
||||
DIFY_API_BASE: str = "https://api.dify.ai/v1"
|
||||
DIFY_API_KEY: str
|
||||
|
||||
# Workflow IDs
|
||||
DIFY_EXAM_WORKFLOW_ID: str # 动态考试工作流
|
||||
DIFY_ASSESSMENT_WORKFLOW_ID: str # 能力评估工作流
|
||||
DIFY_RECOMMEND_WORKFLOW_ID: str # 课程推荐工作流
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
```
|
||||
|
||||
## 环境变量配置(.env.example)
|
||||
```bash
|
||||
# 基础配置
|
||||
DEBUG=true
|
||||
LOG_LEVEL=INFO
|
||||
SECRET_KEY=your-secret-key
|
||||
|
||||
# 数据库配置
|
||||
DATABASE_URL=mysql+aiomysql://user:password@localhost:3306/kaopeilian
|
||||
|
||||
# Coze平台配置
|
||||
COZE_API_BASE=https://api.coze.cn
|
||||
COZE_WORKSPACE_ID=7474971491470688296
|
||||
COZE_API_TOKEN=pat_your_token_here
|
||||
COZE_TRAINING_BOT_ID=7509379008556089379
|
||||
COZE_CHAT_BOT_ID=7509380917472280617
|
||||
|
||||
# Dify平台配置
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=app-your-api-key-here
|
||||
DIFY_EXAM_WORKFLOW_ID=workflow_exam_id
|
||||
DIFY_ASSESSMENT_WORKFLOW_ID=workflow_assessment_id
|
||||
DIFY_RECOMMEND_WORKFLOW_ID=workflow_recommend_id
|
||||
|
||||
# Redis配置(用于缓存和会话)
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
# CORS配置
|
||||
CORS_ORIGINS=["http://localhost:5173", "http://localhost:3000"]
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user