feat: 初始化考培练系统项目
- 从服务器拉取完整代码 - 按框架规范整理项目结构 - 配置 Drone CI 测试环境部署 - 包含后端(FastAPI)、前端(Vue3)、管理端 技术栈: Vue3 + TypeScript + FastAPI + MySQL
This commit is contained in:
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中供后续参考
|
||||
|
||||
祝开发顺利! 🚀
|
||||
Reference in New Issue
Block a user