diff --git a/APILLAMA_FIX_SUMMARY.md b/APILLAMA_FIX_SUMMARY.md deleted file mode 100644 index b8af793..0000000 --- a/APILLAMA_FIX_SUMMARY.md +++ /dev/null @@ -1,239 +0,0 @@ -# APILLAMA处理失败问题修复报告 - -## 问题描述 - -运行 `python scripts/api_flow_tester.py` 时,APILLAMA处理步骤失败: - -``` -[api-flow] ❌ APILLAMA processing failed | payload={'processed': False, 'output_format': 'json_schema', 'schema': None, 'description': None, 'parameters': [], 'examples': [], 'processing_time': 0.0, 'error': None, 'confidence_score': None, 'completeness_score': None} -``` - -## 根本原因 - -**Pydantic验证错误**: `APIParameter` schema要求所有参数必须包含 `location` 字段,但测试脚本和 `_extract_parameters` 方法返回的参数没有包含此字段。 - -### 错误详情 - -```json -{ - "detail": "1 validation error for APILLAMAResponse\nparameters.0.location\n Field required [type=missing, input_value={'name': 'test', 'type': 'string'}, input_type=dict]" -} -``` - -### APIParameter Schema定义 - -```python -class APIParameter(BaseSchema): - """API参数定义""" - name: str = Field(..., description="参数名称") - type: str = Field(..., description="参数类型") - location: str = Field(..., description="参数位置 (query, path, header, body)") # 必需字段 - description: Optional[str] = Field(None, description="参数描述") - required: bool = Field(False, description="是否必需") - # ...其他可选字段 -``` - -## 修复方案 - -### 文件修改 - -**文件**: `services/data-ingestion/apillama_processor.py` - -**修改位置**: `_extract_parameters` 方法 - -### 修改内容 - -#### 1. 处理输入参数时添加location字段 - -```python -# 修改前 -if "parameters" in api_doc: - params = api_doc["parameters"] - if isinstance(params, list): - parameters.extend(params) - -# 修改后 -if "parameters" in api_doc: - params = api_doc["parameters"] - if isinstance(params, list): - for param in params: - # 确保每个参数都有location字段 - if isinstance(param, dict): - if "location" not in param: - param["location"] = "query" # 默认为query参数 - parameters.append(param) -``` - -#### 2. 确保所有参数都有必需字段 - -```python -# 在返回前添加验证 -# 确保所有参数都有必需的字段 -for param in parameters: - if "location" not in param: - param["location"] = "query" - if "type" not in param: - param["type"] = "string" - if "required" not in param: - param["required"] = False -``` - -## 验证结果 - -### 测试用例 - -✅ **测试用例1**: 没有location字段的参数 -- 输入: `[{'name': 'location', 'type': 'string', 'description': 'City name', 'required': True}]` -- 输出: 自动添加 `'location': 'query'` - -✅ **测试用例2**: 有location字段的参数 -- 输入: `[{'name': 'id', 'type': 'string', 'location': 'path', 'required': True}]` -- 输出: location字段保持不变为 `'path'` - -✅ **测试用例3**: 空参数列表 -- 输入: 无参数 -- 输出: 生成默认参数 `[{'name': 'data', 'type': 'object', 'location': 'body', ...}]` - -✅ **测试用例4**: requestBody中的参数 -- 输入: requestBody with properties -- 输出: 所有参数都有 `'location': 'body'` - -### 验证命令 - -```bash -cd /home/taiji/tools/taiji-AI-PAD -python3 verify_apillama_fix.py -``` - -**结果**: ✅ 所有5个参数都包含必需字段: `['name', 'type', 'location', 'required']` - -## 部署步骤 - -### 1. 重启Data Ingestion服务 - -服务已在运行,需要重启以加载修改: - -```bash -# 查找进程 -ps aux | grep -E "(data-ingestion|uvicorn)" | grep -v grep - -# 停止进程 -pkill -f "uvicorn.*data-ingestion" - -# 或者如果使用systemd/docker -sudo systemctl restart data-ingestion -# 或 -docker compose restart data-ingestion -``` - -### 2. 验证修复 - -```bash -# 重新运行测试脚本 -cd /home/taiji/tools/taiji-AI-PAD -python scripts/api_flow_tester.py -``` - -**预期结果**: APILLAMA处理步骤应该成功,不再返回 `processed: False` - -### 3. 手动测试APILLAMA端点 - -```bash -curl -X POST http://localhost:8001/apillama/process \ - -H "Content-Type: application/json" \ - -d '{ - "api_doc": { - "title": "Weather API", - "description": "Returns forecast information", - "parameters": [ - {"name": "location", "type": "string", "description": "City name", "required": true} - ] - }, - "context": {"service": "weather", "version": "1.0"}, - "output_format": "json_schema", - "include_examples": true, - "enhance_descriptions": true, - "validate_schema": true - }' | python3 -m json.tool -``` - -**预期响应**: -```json -{ - "processed": true, - "output_format": "json_schema", - "schema": {...}, - "description": "...", - "parameters": [ - { - "name": "location", - "type": "string", - "location": "query", // ✅ 自动添加 - "description": "City name", - "required": true - } - ], - "examples": [...], - "processing_time": 0.xx, - "confidence_score": 0.xx, - "completeness_score": 0.xx -} -``` - -## 影响范围 - -### 受影响的功能 -- ✅ APILLAMA API文档处理 -- ✅ 工具生成(依赖APILLAMA增强) -- ✅ API流程测试 - -### 不受影响的功能 -- ✅ RapidAPI同步 -- ✅ OpenAPI解析 -- ✅ 工具列表查询 -- ✅ 健康检查 - -## 相关文件 - -- `services/data-ingestion/apillama_processor.py` - 修复的主文件 -- `services/data-ingestion/schemas.py` - APIParameter定义 -- `services/data-ingestion/app/routes/apillama.py` - APILLAMA路由 -- `scripts/api_flow_tester.py` - 测试脚本 -- `verify_apillama_fix.py` - 验证脚本 - -## 预防措施 - -### 1. 添加参数验证 - -在 `_extract_parameters` 方法中添加了完整的字段验证,确保: -- 所有参数都有 `location` 字段 -- 所有参数都有 `type` 字段 -- 所有参数都有 `required` 字段 - -### 2. 默认值策略 - -- `location`: 默认为 `"query"`(最常见的参数位置) -- `type`: 默认为 `"string"`(最通用的类型) -- `required`: 默认为 `False`(更安全的默认值) - -### 3. 测试建议 - -建议在CI/CD流程中添加: -- 参数schema验证测试 -- APILLAMA端点集成测试 -- 边界情况测试(空参数、缺失字段等) - -## 总结 - -✅ **问题已修复**: `_extract_parameters` 方法现在确保所有参数都包含必需的 `location` 字段 - -✅ **验证通过**: 所有测试用例都成功通过 - -⏳ **待完成**: 重启服务并重新运行完整测试 - ---- - -**修复日期**: 2025-12-25 -**修复人**: AI Assistant -**状态**: ✅ 代码已修复,等待服务重启 - diff --git a/BACKEND_IMPLEMENTATION_SUMMARY.md b/BACKEND_IMPLEMENTATION_SUMMARY.md deleted file mode 100644 index f93f708..0000000 --- a/BACKEND_IMPLEMENTATION_SUMMARY.md +++ /dev/null @@ -1,422 +0,0 @@ -# Taiji AI PAD 后端开发完成总结 - -## 项目概述 - -本文档总结了基于前端提供的【用于后端开发的需求与接口文档】(BACKEND_REQUIREMENTS.md v3.0) 对后端代码的完善工作。所有服务已配置为可部署到Azure AKS集群。 - -## 完成的工作 - -### ✅ 1. 数据库模型完善 - -**文件**: `services/mcp-server/models.py` - -完全按照需求文档重构了数据库模型,包括: - -- **User (用户/租户)**: 添加了余额、授信额度、订阅层级等字段 -- **Channel (渠道)**: 完整的渠道管理模型,包含佣金率、授信额度、自定义Agent资源配置 -- **Agent**: 支持平台Agent和自定义Agent,包含资源配置(CPU/内存) -- **ModelProvider (模型供应商)**: 统一的模型供应商管理 -- **ResourceAllocation (资源分配)**: 灵活的资源分配表,支持渠道和租户的Agent/模型资源分配 -- **BillingRecord (计费记录)**: 完整的三维度计费(渠道/租户/调用) -- **RechargeRecord (充值记录)**: 支持用户充值和渠道充值 -- **Application (申请审批)**: 渠道资源申请审批流程 -- **Workflow (工作流)**: 支持最多3个节点的工作流编排 -- **APIKey**: API密钥管理 - -所有模型都包含适当的索引和关联关系,确保查询性能。 - -### ✅ 2. Pydantic Schemas - -**文件**: `services/mcp-server/app/schemas.py` - -创建了完整的API请求/响应数据验证模型: - -- 通用响应格式 (SuccessResponse, ErrorResponse) -- 认证相关 (LoginRequest, TokenResponse等) -- 用户侧平台所有API的请求/响应模型 -- 渠道合作伙伴所有API的请求/响应模型 -- 超级管理员所有API的请求/响应模型 -- 供应商管理API的请求/响应模型 - -### ✅ 3. 认证与权限系统 - -**文件**: `services/mcp-server/app/routes/auth.py` - -实现了完整的认证系统: - -- **POST /api/auth/login**: 支持四种角色登录(user/channel/admin/provider) -- **POST /api/auth/logout**: 用户登出 -- **POST /api/auth/refresh**: Token刷新 -- **PUT /api/auth/password**: 修改密码 -- **GET /api/auth/keys/info**: 获取API密钥信息 -- **POST /api/auth/keys/regenerate**: 重新生成API密钥 - -所有接口都包含适当的权限验证和错误处理。 - -### ✅ 4. 用户侧平台API - -**文件**: `services/mcp-server/app/routes/user.py` - -实现了需求文档中所有用户侧API: - -**概览**: -- GET /api/user/dashboard/stats - 仪表板统计 -- GET /api/user/agents/activity - Agent活动图表 - -**服务网关**: -- POST /api/user/gateway/select - 选择网关类型 -- POST /api/user/gateway/api/create - 创建API -- GET /api/user/gateway/apis - 获取API列表 -- GET /api/user/gateway/monitoring - 监控数据 - -**数据与工具**: -- POST /api/user/tools/generate - 生成工具 -- POST /api/user/data-templates/create - 创建数据模板 - -**代理工厂**: -- GET /api/user/agents/platform - 获取平台Agent列表 -- POST /api/user/agents/deploy - 部署Agent - -**编排中心**: -- POST /api/user/workflows/create - 创建工作流(最多3节点验证) - -**计费与资源**: -- GET /api/user/billing/balance - 获取余额信息 -- POST /api/user/billing/recharge - 充值余额 -- GET /api/user/billing/history - 获取计费历史(支持导出) - -### ✅ 5. 渠道合作伙伴API - -**文件**: `services/mcp-server/app/routes/channel.py` - -实现了所有渠道管理功能: - -**租户管理**: -- GET /api/channel/tenants - 获取租户列表 -- POST /api/channel/tenants/create - 创建租户 -- PUT /api/channel/tenants/{id}/resources - 分配资源 -- PUT /api/channel/tenants/{id}/billing - 更新计费设置 -- POST /api/channel/tenants/{id}/recharge - 为租户充值 -- PUT /api/channel/tenants/{id}/credit - 设置授信额度 - -**资源申请**: -- POST /api/channel/resources/apply - 申请资源(模型/Agent) - -**计费统计**: -- GET /api/channel/billing/stats - 渠道计费统计(支持筛选和导出) - -### ✅ 6. 超级管理员API - -**文件**: `services/mcp-server/app/routes/admin.py` - -实现了平台管理功能: - -**概览**: -- GET /api/admin/dashboard/stats - 平台全局统计 - -**渠道管理**: -- GET /api/admin/channels - 获取所有渠道 -- POST /api/admin/channels/create - 创建渠道 -- PUT /api/admin/channels/{id}/resources - 统一资源管理 - -**申请审批**: -- GET /api/admin/channels/applications - 获取所有申请 -- PUT /api/admin/channels/applications/{id}/review - 审批申请 - -**资源管理**: -- GET /api/admin/resources/models - 获取所有模型供应商 -- GET /api/admin/resources/agents - 获取所有Agent - -**监控**: -- GET /api/admin/monitoring/agents - Agent健康状态监控 - -**计费(三维度)**: -- GET /api/admin/billing/overview - 三维度计费统计(渠道/租户/调用) - -### ✅ 7. 供应商管理API - -**文件**: `services/mcp-server/app/routes/providers.py` - -实现了模型供应商配置: - -- GET /api/providers/models - 获取所有模型供应商 -- POST /api/providers/models/create - 创建模型供应商 -- GET /api/providers/models/{id} - 获取供应商详情 -- PUT /api/providers/models/{id} - 更新供应商配置 -- DELETE /api/providers/models/{id} - 删除供应商 -- POST /api/providers/models/{id}/test - 测试连接 - -包含API密钥加密存储功能。 - -### ✅ 8. 计费与资源管理逻辑 - -**文件**: `services/mcp-server/app/billing.py` - -实现了完整的计费引擎: - -**EU计算**: -- `calculate_eu()`: 1 EU = 10秒,不足10秒按1 EU计算 -- `calculate_cost()`: 1 EU = ¥0.01(可配置) - -**余额管理**: -- `get_available_balance()`: 获取可用额度 = 账户余额 + 授信额度 -- `check_balance_sufficient()`: 检查余额是否充足 -- `deduct_balance()`: 扣除余额(优先扣除账户余额) -- `add_balance()`: 增加余额 - -**计费记录**: -- `create_billing_record()`: 创建计费记录并自动扣费 - -**资源配额**: -- `check_agent_quota()`: 检查Agent配额 -- `check_model_quota()`: 检查模型RPM/TPM配额 -- `validate_resource_allocation()`: 验证资源分配层级 - -**工作流验证**: -- `validate_workflow_nodes()`: 验证工作流最多3个节点 - -**统计函数**: -- `calculate_monthly_cost()`: 计算月度消费 -- `calculate_channel_commission()`: 计算渠道佣金 - -### ✅ 9. Azure AKS部署配置 - -创建了完整的Kubernetes部署配置: - -**K8s配置文件**: -- `k8s/deployment.yaml`: Deployment、Service、HPA、PDB配置 - - 3-10副本自动扩缩容 - - CPU/内存资源限制 - - 健康检查配置 - - Azure ACR镜像拉取 - -- `k8s/secrets.yaml`: Secrets配置模板 - - 数据库连接字符串 - - Redis连接字符串 - - JWT和加密密钥 - - Azure存储配置 - -- `k8s/ingress.yaml`: Ingress配置 - - Application Gateway Ingress Controller - - SSL/TLS终止 - - 路由规则 - -**Docker配置**: -- `Dockerfile`: 多阶段构建,优化镜像大小 -- `requirements.txt`: Python依赖包列表 - -**部署脚本**: -- `scripts/deploy-azure.sh`: 一键部署脚本 - - 自动创建ACR - - 构建并推送镜像 - - 部署到AKS - - 配置验证 - -**部署文档**: -- `DEPLOY_AZURE.md`: 详细的部署指南 - - 前置条件 - - 快速部署步骤 - - 手动部署详解 - - 监控和日志 - - 故障排查 - - 安全最佳实践 - -### ✅ 10. 配置更新 - -**文件**: `services/mcp-server/config.py` - -更新配置以使用需求文档中的实际Azure资源: - -- 数据库URL: `taijipda.postgres.database.azure.com` -- Redis URL: `taiji.southeastasia.redis.azure.net` -- JWT密钥: `zsbgnw` -- 加密密钥: `zsbgnw` -- 支持环境变量覆盖 - -## 技术栈 - -- **Web框架**: FastAPI + Uvicorn -- **数据库**: PostgreSQL (Azure Database for PostgreSQL) -- **缓存**: Redis (Azure Cache for Redis) -- **ORM**: SQLAlchemy (async) -- **认证**: JWT + API Key -- **密码哈希**: bcrypt -- **密钥加密**: Fernet (cryptography) -- **容器化**: Docker -- **编排**: Kubernetes (Azure AKS) -- **Ingress**: Azure Application Gateway - -## 数据库架构 - -``` -Users (租户) - ├── balance (余额) - ├── credit_limit (授信额度) - └── channel_id → Channels - -Channels (渠道) - ├── commission_rate (佣金率) - ├── channel_credit (授信额度) - └── custom_agent_resources (自定义Agent资源) - -Agents (Agent) - ├── type (platform/custom) - ├── cpu, memory (资源配置) - └── owner_id → Users - -ResourceAllocations (资源分配) - ├── target_type (channel/tenant) - ├── resource_type (agent/model) - └── quantity, rpm, tpm - -BillingRecords (计费记录) - ├── channel_id → Channels - ├── tenant_id → Users - ├── agent_id → Agents - ├── duration, eu, cost - └── timestamp - -Applications (申请审批) - ├── channel_id → Channels - ├── type (model/agent) - ├── status (pending/approved/rejected) - └── details (申请详情) - -Workflows (工作流) - ├── user_id → Users - ├── nodes (最多3个) - └── gateway (MCP/A2A/API) -``` - -## API端点概览 - -### 认证 (/api/auth) -- POST /login - 登录 -- POST /logout - 登出 -- POST /refresh - 刷新Token -- PUT /password - 修改密码 -- GET /keys/info - 获取API密钥 -- POST /keys/regenerate - 重新生成密钥 - -### 用户侧 (/api/user) -- 概览: dashboard/stats, agents/activity -- 网关: gateway/* -- 工具: tools/*, data-templates/* -- Agent: agents/platform, agents/deploy -- 工作流: workflows/create -- 计费: billing/balance, billing/recharge, billing/history - -### 渠道 (/api/channel) -- 租户: tenants, tenants/create, tenants/{id}/* -- 资源: resources/apply -- 计费: billing/stats - -### 管理员 (/api/admin) -- 概览: dashboard/stats -- 渠道: channels, channels/create, channels/{id}/* -- 申请: channels/applications, channels/applications/{id}/review -- 资源: resources/models, resources/agents -- 监控: monitoring/agents -- 计费: billing/overview - -### 供应商 (/api/providers) -- 模型: models, models/create, models/{id}, models/{id}/test - -## 业务规则实现 - -✅ **EU计算规则**: 1 EU = 10秒,不足10秒按1 EU计算 -✅ **计费价格**: 1 EU = ¥0.01(可配置) -✅ **余额与授信**: 可用额度 = 账户余额 + 授信额度 -✅ **资源分配层级**: 超级管理员 → 渠道 → 租户 -✅ **工作流限制**: 最多3个Agent节点 -✅ **平台Agent资源**: CPU 2核,内存 4GB(固定) -✅ **自定义Agent资源**: 由上级分配 - -## 部署架构 - -``` -Azure Cloud -├── AKS Cluster (Kubernetes) -│ ├── MCP Server Pods (3-10 replicas) -│ ├── Application Gateway Ingress -│ └── Persistent Volumes -├── Azure Database for PostgreSQL -├── Azure Cache for Redis -├── Azure Container Registry (ACR) -├── Azure Blob Storage (导出文件) -└── Azure Key Vault (密钥管理) -``` - -## 安全特性 - -✅ JWT认证 -✅ API密钥认证 -✅ bcrypt密码哈希 -✅ 模型供应商API密钥加密存储 -✅ HTTPS/TLS (通过Ingress) -✅ CORS配置 -✅ 连接字符串SSL模式 -✅ Secrets管理 - -## 性能优化 - -✅ 数据库连接池 -✅ Redis缓存 -✅ 异步I/O (AsyncIO) -✅ 数据库索引优化 -✅ HPA自动扩缩容 -✅ 资源请求/限制配置 -✅ 健康检查和就绪探针 - -## 监控和可观测性 - -✅ 健康检查端点 (/health) -✅ Prometheus metrics端点 (/metrics) -✅ 结构化日志 (JSON格式) -✅ Pod资源监控 -✅ Azure Monitor集成支持 - -## 下一步建议 - -虽然后端核心功能已完成,但可以考虑以下增强: - -1. **数据库迁移**: 使用Alembic管理数据库版本 -2. **单元测试**: 添加pytest测试用例 -3. **API文档**: 完善Swagger/OpenAPI文档 -4. **速率限制**: 添加API速率限制中间件 -5. **日志聚合**: 集成ELK或Azure Monitor -6. **APM**: 添加应用性能监控(如Application Insights) -7. **备份策略**: 自动化数据库和配置备份 -8. **CI/CD**: GitHub Actions或Azure DevOps流水线 -9. **环境隔离**: dev/staging/production环境配置 -10. **安全审计**: 定期安全扫描和漏洞评估 - -## 部署清单 - -在部署到生产环境之前,请确认: - -- [ ] 更新 `k8s/secrets.yaml` 中的所有密钥和连接字符串 -- [ ] 配置Azure Database for PostgreSQL防火墙规则 -- [ ] 配置Azure Cache for Redis访问控制 -- [ ] 创建Azure Storage Account和容器 -- [ ] 配置Application Gateway和SSL证书 -- [ ] 设置DNS记录指向Application Gateway -- [ ] 配置备份策略 -- [ ] 设置监控告警 -- [ ] 执行数据库初始化(创建表和初始数据) -- [ ] 测试所有API端点 -- [ ] 负载测试 -- [ ] 安全扫描 - -## 联系方式 - -如有问题或需要支持,请联系: -- Email: admin@taiji-ai.com -- 文档: 参见 DEPLOY_AZURE.md - ---- - -**完成时间**: 2025-12-25 -**版本**: v1.0 -**状态**: ✅ 生产就绪 - diff --git a/BACKEND_INTEGRATION_CHECKLIST.md b/BACKEND_INTEGRATION_CHECKLIST.md deleted file mode 100644 index ef07054..0000000 --- a/BACKEND_INTEGRATION_CHECKLIST.md +++ /dev/null @@ -1,704 +0,0 @@ -# Taiji AI Platform - 后端开发对接清单 - -## 系统架构概述 - -Taiji AI Platform 是一个多租户AI Agent管理平台,包含以下四个主要系统: - -1. **用户侧平台** (User Dashboard) - `/` -2. **渠道合作伙伴平台** (Channel Partner Platform) - `/channel` -3. **超级管理员控制台** (Super Admin Console) - `/admin` -4. **平台供应商管理中心** (Provider Management Center) - `/admin/providers` - ---- - -## 一、核心业务模块 - -### 1. 用户侧平台 (User Dashboard) - -#### 1.1 概览 (Overview) - `/` -**功能**:系统状态、Agent活动、资源消耗监控 -**需要的API**: -- `GET /api/user/dashboard/stats` - 获取统计数据 - ```json - { - "activeAgents": number, - "totalRequests": number, - "euBalance": number, - "systemHealth": number - } - ``` -- `GET /api/user/agents/activity` - Agent活动数据 -- `GET /api/user/resources/usage` - 资源使用情况 - -#### 1.2 服务网关 (Service Gateway) - `/model-gateway` -**功能**:选择服务网关类型(MCP/A2A/API),创建API接口 -**需要的API**: -- `POST /api/gateway/select` - 选择网关类型 - ```json - { - "gatewayType": "MCP" | "A2A" | "API" - } - ``` -- `POST /api/gateway/api/create` - 创建API(支持JSON文档或URL) - ```json - { - "name": string, - "method": "json" | "url", - "content": string | File - } - ``` -- `GET /api/gateway/apis` - 获取API列表 -- `GET /api/gateway/monitoring` - 监控数据 - -#### 1.3 数据与工具 (Data & Tools) - `/data-tools` -**功能**:数据模板管理、工具生成、Pod部署 -**需要的API**: -- `POST /api/tools/generate` - 生成新工具 - ```json - { - "name": string, - "description": string, - "frameworkTemplate": "MCP" | "A2A" | "API", - "gateway": string, - "agentCount": number, - "cpu": number, - "memory": number, - "maxScale": number, - "model": string - } - ``` -- `GET /api/tools/list` - 工具列表 -- `POST /api/data-templates/create` - 创建数据模板 - ```json - { - "name": string, - "type": "json_api" | "cloud_storage", - "config": { - "apiUrl"?: string, - "queryParams"?: Record, - "cloudProvider"?: "azure" | "gcp" | "aws", - "connectionString"?: string - } - } - ``` - -#### 1.4 代理工厂 (Agent Factory) - `/agent-factory` -**功能**:展示和部署平台原生Agent -**需要的API**: -- `GET /api/agents/platform` - 获取平台原生Agent列表 -- `POST /api/agents/deploy` - 部署Agent - ```json - { - "agentId": string, - "instances": number, - "model": string, - "gateway": "MCP" | "A2A" | "API" - } - ``` -- `GET /api/agents/deployed` - 获取已部署Agent - -#### 1.5 编排中心 (Orchestration Hub) - `/orchestration` -**功能**:创建工作流,最多3个Agent节点 -**需要的API**: -- `POST /api/workflows/create` - 创建工作流 - ```json - { - "name": string, - "description": string, - "gateway": "MCP" | "A2A" | "API", - "nodes": Array<{ - "agentId": string, - "agentType": "platform" | "custom", - "agentName": string - }> // 最多3个 - } - ``` -- `GET /api/workflows/list` - 工作流列表 -- `PUT /api/workflows/{id}` - 更新工作流 -- `DELETE /api/workflows/{id}` - 删除工作流 - -#### 1.6 计费与资源 (Billing & Resources) - `/billing` -**功能**:EU余额、使用记录、充值 -**需要的API**: -- `GET /api/billing/balance` - 获取EU余额 -- `GET /api/billing/history` - 使用历史 - ```json - { - "records": Array<{ - "timestamp": string, - "agentName": string, - "duration": number, - "eu": number, // 1 EU = 10秒 - "cost": number - }> - } - ``` -- `POST /api/billing/recharge` - 充值 - ---- - -### 2. 渠道合作伙伴平台 (Channel Partner) - -#### 2.1 登录 - `/channel/login` -**需要的API**: -- `POST /api/channel/auth/login` - ```json - { - "email": string, - "password": string - } - ``` - -#### 2.2 概览 - `/channel/dashboard` -**需要的API**: -- `GET /api/channel/dashboard/stats` - 渠道统计数据 -- `GET /api/channel/agents/available` - 可分配Agent列表及数量 - -#### 2.3 租户管理 - `/channel/dashboard` (Tenants Tab) -**需要的API**: -- `GET /api/channel/tenants` - 租户列表 -- `POST /api/channel/tenants/create` - 创建租户 -- `PUT /api/channel/tenants/{id}/resources` - 分配资源 - ```json - { - "agents": Array<{ - "agentId": string, - "quantity": number - }>, - "models": Array<{ - "modelId": string, - "rpm": number, - "tpm": number - }>, - "customAgentResources": { - "cpu": number, - "memory": number - } - } - ``` -- `PUT /api/channel/tenants/{id}/billing` - 管理计费 - ```json - { - "subscriptionTier": "free" | "pro" | "enterprise", - "discount": number // 0-100 - } - ``` - -#### 2.4 资源管理 - `/channel/dashboard` (Resources Tab) -**需要的API**: -- `GET /api/channel/resources/agents` - Agent配额 -- `GET /api/channel/resources/models` - 已分配模型 -- `POST /api/channel/resources/apply` - 提交申请 - ```json - { - "type": "model" | "agent", - "modelName"?: string, - "rpm"?: number, - "tpm"?: number, - "agentType"?: string, - "quantity"?: number, - "reason": string - } - ``` - -#### 2.5 计费 - `/channel/dashboard` (Billing Tab) -**需要的API**: -- `GET /api/channel/billing/stats` - 计费统计(租户维度 + 调用记录) - -#### 2.6 设置 - `/channel/dashboard` (Settings Tab) -**需要的API**: -- `GET /api/channel/admins` - 管理员列表 -- `POST /api/channel/admins/create` - 创建管理员 - ```json - { - "name": string, - "email": string, - "password": string, - "role": "billing_admin" | "operations_admin", - "permissions": string[] - } - ``` -- `PUT /api/channel/admins/{id}/permissions` - 更新权限 - ---- - -### 3. 超级管理员控制台 (Super Admin) - -#### 3.1 登录 - `/admin/login` -**需要的API**: -- `POST /api/admin/auth/login` - -#### 3.2 概览 - `/admin/dashboard` -**需要的API**: -- `GET /api/admin/dashboard/stats` - 平台全局统计 - -#### 3.3 渠道管理 - `/admin/dashboard` (Channels Tab) -**需要的API**: -- `GET /api/admin/channels` - 渠道列表 -- `POST /api/admin/channels/create` - 创建渠道 - ```json - { - "name": string, - "email": string, - "commissionRate": number // 0-100 - } - ``` -- `PUT /api/admin/channels/{id}/commission` - 修改佣金 -- `PUT /api/admin/channels/{id}/resources` - 资源管理(模型+数据源+Agent+配额) - ```json - { - "models": string[], - "dataSources": string[], - "agents": Array<{ - "agentId": string, - "quantity": number - }>, - "customAgentResources": { - "cpu": number, - "memory": number - }, - "monthlyQuota": number, - "monthlyBudget": number - } - ``` -- `GET /api/admin/channels/applications` - 渠道申请列表 -- `PUT /api/admin/channels/applications/{id}/approve` - 审批申请 - ```json - { - "approved": boolean, - "reason"?: string - } - ``` - -#### 3.4 资源管理 - `/admin/dashboard` (Resources Tab) -**需要的API**: -- `GET /api/admin/resources/models` - 模型供应商列表 -- `POST /api/admin/resources/models/add` - 添加模型供应商 - ```json - { - "name": string, - "apiUrl": string, - "apiKey": string, - "supportedModels": string[], - "rpm": number, - "tpm": number - } - ``` -- `GET /api/admin/resources/agents` - Agent资源列表 -- `PUT /api/admin/resources/agents/{id}` - 配置Agent资源 - ```json - { - "cpu": number, - "memory": number, - "maxInstances": number - } - ``` - -#### 3.5 监控 - `/admin/dashboard` (Monitoring Tab) -**需要的API**: -- `GET /api/admin/monitoring/agents` - Agent健康状态 - -#### 3.6 计费 - `/admin/dashboard` (Billing Tab) -**需要的API**: -- `GET /api/admin/billing/overview` - 计费概览(渠道+租户+调用明细) - ```json - { - "channels": Array<{ - "channelName": string, - "calls": number, - "totalEU": number, - "totalCost": number - }>, - "tenants": Array<{ - "tenantName": string, - "channelName": string, - "calls": number, - "totalEU": number, - "totalCost": number - }>, - "callRecords": Array<{ - "timestamp": string, // 精确到时分秒 - "channelName": string, - "tenantName": string, - "agentName": string, - "duration": number, // 秒 - "eu": number, // 1 EU = 10秒 - "cost": number - }> - } - ``` - -#### 3.7 设置 - `/admin/dashboard` (Settings Tab) -**需要的API**: -- `GET /api/admin/roles` - 角色列表 -- `POST /api/admin/admins/create` - 创建管理员 - ```json - { - "name": string, - "email": string, - "password": string, - "role": "billing_admin" | "operations_admin" | "super_admin", - "permissions": string[] - } - ``` - -#### 3.8 供应商管理中心后台 - `/admin/dashboard` (Provider Backend Tab) -**需要的API**: -- `GET /api/admin/providers/stats` - 供应商运营数据 - -#### 3.9 渠道管理中心后台 - `/admin/dashboard` (Channel Backend Tab) -**需要的API**: -- `GET /api/admin/channels/backend/stats` - 渠道后台数据 - ---- - -### 4. 平台供应商管理中心 - -#### 4.1 登录 - `/admin/providers/login` -**需要的API**: -- `POST /api/providers/auth/login` - -#### 4.2 管理中心 - `/admin/providers` -**需要的API**: -- `GET /api/providers/models` - 模型供应商列表 -- `POST /api/providers/models/add` - 添加模型供应商(支持多云平台) -- `GET /api/providers/data` - 数据供应商(RapidAPI) - ---- - -## 二、数据模型设计建议 - -### 1. 用户/租户表 (Users/Tenants) -```typescript -{ - id: string - name: string - email: string - role: "user" | "channel_admin" | "super_admin" | "provider_admin" - channelId?: string // 所属渠道 - subscriptionTier: "free" | "pro" | "enterprise" - discount: number - createdAt: Date - updatedAt: Date -} -``` - -### 2. 渠道表 (Channels) -```typescript -{ - id: string - name: string - email: string - commissionRate: number - monthlyQuota: number - monthlyBudget: number - createdAt: Date - updatedAt: Date -} -``` - -### 3. Agent表 (Agents) -```typescript -{ - id: string - name: string - type: "platform" | "custom" - description: string - cpu: number - memory: number - maxInstances: number - status: "active" | "inactive" | "deploying" - createdAt: Date - updatedAt: Date -} -``` - -### 4. 模型供应商表 (Model Providers) -```typescript -{ - id: string - name: string - source: "openai" | "anthropic" | "google" | "azure" | "aws" | "openroute" - apiUrl: string - apiKey: string - supportedModels: string[] - rpm: number - tpm: number - status: "active" | "inactive" - createdAt: Date - updatedAt: Date -} -``` - -### 5. 资源分配表 (Resource Allocations) -```typescript -{ - id: string - targetId: string // channelId 或 tenantId - targetType: "channel" | "tenant" - resourceType: "agent" | "model" - resourceId: string - quantity?: number // Agent数量 - rpm?: number // 模型RPM - tpm?: number // 模型TPM - customAgentCpu?: number - customAgentMemory?: number - createdAt: Date - updatedAt: Date -} -``` - -### 6. 计费记录表 (Billing Records) -```typescript -{ - id: string - timestamp: Date // 精确到秒 - channelId: string - tenantId: string - agentId: string - agentName: string - duration: number // 秒 - eu: number // 1 EU = 10秒 - cost: number - createdAt: Date -} -``` - -### 7. 申请审批表 (Applications) -```typescript -{ - id: string - channelId: string - type: "model" | "agent" - // 模型申请 - modelName?: string - rpm?: number - tpm?: number - // Agent申请 - agentType?: string - quantity?: number - // 通用 - reason: string - status: "pending" | "approved" | "rejected" - reviewedBy?: string - reviewedAt?: Date - createdAt: Date - updatedAt: Date -} -``` - -### 8. 工作流表 (Workflows) -```typescript -{ - id: string - userId: string - name: string - description: string - gateway: "MCP" | "A2A" | "API" - nodes: Array<{ - agentId: string - agentType: "platform" | "custom" - agentName: string - order: number - }> - status: "active" | "inactive" - createdAt: Date - updatedAt: Date -} -``` - ---- - -## 三、认证与权限 - -### 1. JWT Token 结构 -```typescript -{ - userId: string - role: "user" | "channel_admin" | "super_admin" | "provider_admin" - channelId?: string - permissions: string[] - exp: number -} -``` - -### 2. 权限列表 -- `view:overview` - 查看概览 -- `manage:tenants` - 管理租户 -- `manage:resources` - 管理资源 -- `view:billing` - 查看计费 -- `manage:billing` - 管理计费 -- `view:settings` - 查看设置 -- `manage:settings` - 管理设置 -- `approve:applications` - 审批申请 - ---- - -## 四、环境变量配置 - -前端已配置的环境变量: -```bash -NEXT_PUBLIC_DATA_INGESTION_URL=http://localhost:8001 -NEXT_PUBLIC_MCP_SERVER_URL=http://localhost:8000 -NEXT_PUBLIC_API_GATEWAY_URL=http://localhost:80 -``` - -建议后端环境变量: -```bash -DATABASE_URL=postgresql://... -REDIS_URL=redis://... -JWT_SECRET=... -ENCRYPTION_KEY=... -``` - ---- - -## 五、关键业务逻辑 - -### 1. EU计算规则 -- **1 EU = 10秒调用时间** -- 计费公式:`EU = Math.ceil(duration / 10)` -- 不足10秒按10秒计算 - -### 2. 资源分配层级 -``` -超级管理员 - ↓ 分配资源到渠道 -渠道管理员 - ↓ 分配资源到租户 -租户 - ↓ 使用资源 -``` - -### 3. 服务网关选择 -- 用户在创建Agent、工具、工作流时必须选择服务网关类型 -- 支持三种类型:MCP、A2A、API - -### 4. Agent部署 -- 平台Agent:固定CPU(2核)、内存(4GB) -- 自定义Agent:由渠道/超级管理员分配资源 - -### 5. 工作流限制 -- 最多3个Agent节点 -- 支持平台Agent + 自定义Agent混合 - ---- - -## 六、国际化支持 - -前端已实现完整的中英文切换,后端返回数据建议: -1. 错误消息使用错误码,由前端翻译 -2. 动态数据(如Agent名称)保持原样 -3. 系统消息可以包含国际化字段 - ---- - -## 七、前端已完成功能检查 - -✅ **用户侧平台** -- ✅ 概览 -- ✅ 服务网关(MCP/A2A/API选择、API创建) -- ✅ 数据与工具(数据模板、工具生成、Pod部署) -- ✅ 代理工厂(平台Agent展示、部署配置) -- ✅ 编排中心(工作流创建、最多3节点) -- ✅ 计费与资源 -- ✅ 完整国际化 - -✅ **渠道合作伙伴平台** -- ✅ 登录 -- ✅ 概览(可分配Agent展示) -- ✅ 租户管理(资源分配、计费管理) -- ✅ 资源管理(模型申请、Agent申请) -- ✅ 计费(租户+调用记录) -- ✅ 设置(角色权限) -- ✅ 完整国际化 -- ✅ 修改密码功能 - -✅ **超级管理员控制台** -- ✅ 登录 -- ✅ 概览 -- ✅ 渠道管理(创建、佣金、资源管理、申请审批) -- ✅ 资源管理(模型供应商、Agent配置) -- ✅ 监控(Agent健康) -- ✅ 计费(三维度:渠道+租户+调用) -- ✅ 设置(角色管理) -- ✅ 供应商/渠道管理后台 -- ✅ 完整国际化 - -✅ **平台供应商管理中心** -- ✅ 登录 -- ✅ 模型管理(多云平台支持) -- ✅ 完整国际化 - ---- - -## 八、待后端实现的核心功能 - -### 高优先级 -1. ✅ 认证系统(JWT) -2. ✅ 用户/渠道/租户CRUD -3. ✅ 资源分配逻辑 -4. ✅ 计费系统(EU计算) -5. ✅ 申请审批流程 - -### 中优先级 -6. ✅ Agent部署管理 -7. ✅ 工作流执行引擎 -8. ✅ 服务网关路由 -9. ✅ 监控数据采集 - -### 低优先级 -10. ✅ WebSocket实时通信 -11. ✅ 数据模板处理 -12. ✅ 工具自动生成 - ---- - -## 九、API响应格式建议 - -### 成功响应 -```json -{ - "success": true, - "data": { ... }, - "message": "操作成功" -} -``` - -### 错误响应 -```json -{ - "success": false, - "error": { - "code": "AUTH_FAILED", - "message": "认证失败" - } -} -``` - ---- - -## 十、下一步行动 - -1. **后端团队**: - - 根据此文档设计数据库Schema - - 实现认证系统 - - 实现核心API端点(建议按优先级) - - 编写API文档(Swagger/OpenAPI) - -2. **前端团队**: - - 等待后端API文档 - - 对接API(替换Mock数据) - - 联调测试 - - 性能优化 - -3. **测试团队**: - - 准备测试用例 - - 集成测试 - - 压力测试 - ---- - -**文档版本**: v1.0 -**最后更新**: 2025-01-08 -**维护者**: Taiji AI Platform Team diff --git a/BACKEND_REQUIREMENTS.md b/BACKEND_REQUIREMENTS.md deleted file mode 100644 index b2f8760..0000000 --- a/BACKEND_REQUIREMENTS.md +++ /dev/null @@ -1,941 +0,0 @@ -# Taiji AI Platform - 后端开发需求与接口文档 - -**版本**: v3.0 -**更新日期**: 2025-01-08 -**状态**: 前端设计完成,待后端开发 - ---- - -## 目录 - -1. [系统概述](#系统概述) -2. [四大子系统功能清单](#四大子系统功能清单) -3. [完整API接口规范](#完整api接口规范) -4. [数据库设计](#数据库设计) -5. [业务规则](#业务规则) -6. [认证与权限](#认证与权限) -7. [部署要求](#部署要求) - ---- - -## 系统概述 - -### 平台架构 - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ Taiji AI Platform │ -├─────────────────┬─────────────────┬─────────────────┬───────────┤ -│ 用户侧平台 │ 渠道合作伙伴 │ 超级管理员 │ 供应商 │ -│ (租户使用) │ 平台 │ 控制台 │ 管理中心 │ -├─────────────────┴─────────────────┴─────────────────┴───────────┤ -│ API Gateway │ -├──────────────────────────────────────────────────────────────────┤ -│ 服务网关 (MCP/A2A/API) │ 计费引擎 │ 资源调度 │ 监控系统 │ -├──────────────────────────────────────────────────────────────────┤ -│ 数据库 & 缓存 │ -│ PostgreSQL │ Redis │ S3 │ -└──────────────────────────────────────────────────────────────────┘ -``` - -### 核心服务端口 -| 服务 | 端口 | 说明 | -|------|------|------| -| Next.js 前端 | 3000 | 主应用 | -| API网关 | 80/443 | 外部访问 | -| MCP服务 | 8000 | MCP协议服务 | -| 数据摄取 | 8001 | 数据处理服务 | - ---- - -## 四大子系统功能清单 - -### 1. 用户侧平台 (/) - -| 页面 | 功能模块 | 核心功能 | -|------|----------|----------| -| 概览 | 仪表板 | 统计数据、Agent活动图表、资源使用情况 | -| 服务网关 | 网关管理 | 选择网关类型(MCP/A2A/API)、创建API(JSON/URL)、监控 | -| 数据与工具 | 工具管理 | 数据模板、工具生成、Pod部署配置 | -| 代理工厂 | Agent管理 | 平台Agent展示、部署配置 | -| 编排中心 | 工作流 | 创建工作流(最多3节点)、运行管理 | -| 计费与资源 | 计费 | **余额显示、充值、使用记录、筛选、导出** | -| 密钥管理 | 安全 | 服务终结点、API密钥查看与更新 | - -### 2. 渠道合作伙伴平台 (/channel) - -| 页面 | 功能模块 | 核心功能 | -|------|----------|----------| -| 概览 | 仪表板 | 渠道统计、可分配Agent概览 | -| 租户管理 | 租户 | 创建租户、分配资源、管理计费、**充值、授信额度** | -| 资源管理 | 资源 | Agent配额监控、模型管理、**提交申请(模型/Agent)** | -| 计费 | 计费 | 租户计费统计、调用记录、筛选、导出 | -| 设置 | 权限 | 管理员角色(计费/运营)、权限配置 | - -### 3. 超级管理员控制台 (/admin) - -| 页面 | 功能模块 | 核心功能 | -|------|----------|----------| -| 概览 | 仪表板 | 平台全局统计 | -| 渠道管理 | 渠道 | 创建渠道、佣金设置、**统一资源管理**、申请审批 | -| 资源管理 | 资源 | 模型供应商、Agent计算资源配置 | -| 监控 | 监控 | Agent健康状态、性能指标 | -| 计费 | 计费 | 三维度计费(渠道/租户/调用)、筛选、导出 | -| 设置 | 权限 | 管理员角色(计费/运营/超级)、权限配置 | - -### 4. 供应商管理中心 (/admin/providers) - -| 页面 | 功能模块 | 核心功能 | -|------|----------|----------| -| 模型管理 | 供应商 | 多云模型供应商配置 | - ---- - -## 完整API接口规范 - -### 通用响应格式 - -```typescript -// 成功响应 -{ - "success": true, - "data": { ... }, - "message"?: string -} - -// 错误响应 -{ - "success": false, - "error": { - "code": string, - "message": string - } -} -``` - -### 一、认证模块 - -#### POST /api/auth/login -```typescript -Request: -{ - "email": string, - "password": string, - "role": "user" | "channel" | "admin" | "provider" -} - -Response: -{ - "success": true, - "data": { - "token": string, - "refreshToken": string, - "user": { - "id": string, - "name": string, - "email": string, - "role": string, - "channelId"?: string - } - } -} -``` - -#### POST /api/auth/logout -#### POST /api/auth/refresh -#### PUT /api/auth/password - -### 二、密钥管理模块 - -#### GET /api/keys/info -获取服务终结点和API密钥 -```typescript -Response: -{ - "success": true, - "data": { - "endpoint": "https://api.taiji-ai.com/v1", - "apiKey": "sk-xxxx...xxxx", // 部分隐藏 - "createdAt": string, - "lastUsed": string - } -} -``` - -#### POST /api/keys/regenerate -重新生成API密钥 -```typescript -Response: -{ - "success": true, - "data": { - "apiKey": "sk-新密钥完整显示", - "message": "旧密钥已失效" - } -} -``` - -### 三、用户侧API - -#### 3.1 概览 - -##### GET /api/user/dashboard/stats -```typescript -Response: -{ - "activeAgents": number, - "totalRequests": number, - "euBalance": number, - "systemHealth": number -} -``` - -##### GET /api/user/agents/activity -```typescript -Query: { period: "7d" | "30d" | "90d" } -Response: -{ - "data": Array<{ - "date": string, - "agentName": string, - "requests": number - }> -} -``` - -#### 3.2 服务网关 - -##### POST /api/gateway/select -```typescript -Request: -{ - "gatewayType": "MCP" | "A2A" | "API" -} -``` - -##### POST /api/gateway/api/create -```typescript -Request: -{ - "name": string, - "method": "json" | "url", - "content": string // JSON文档或URL -} -``` - -##### GET /api/gateway/apis -##### GET /api/gateway/monitoring - -#### 3.3 数据与工具 - -##### POST /api/tools/generate -```typescript -Request: -{ - "name": string, - "description": string, - "frameworkTemplate": "MCP" | "A2A" | "API", - "gateway": string, // 网关ID - "agentCount": number, - "cpu": number, - "memory": number, - "maxScale": number, - "model": string -} -``` - -##### POST /api/data-templates/create -```typescript -Request (JSON API): -{ - "name": string, - "type": "json_api", - "config": { - "apiUrl": string, - "queryParams": Record - } -} - -Request (云存储): -{ - "name": string, - "type": "cloud_storage", - "config": { - "provider": "azure" | "gcp" | "aws", - "service": "blob" | "s3" | "gcs", - "connectionString": string - } -} - -Request (数据库): -{ - "name": string, - "type": "database", - "config": { - "type": "postgresql" | "mysql" | "mongodb" | "snowflake" | "databricks", - "connectionString": string - } -} -``` - -#### 3.4 代理工厂 - -##### GET /api/agents/platform -```typescript -Response: -{ - "data": Array<{ - "id": string, - "name": string, - "description": string, - "category": string, - "cpu": number, // 固定2核 - "memory": number, // 固定4GB - "status": "available" | "unavailable" - }> -} -``` - -##### POST /api/agents/deploy -```typescript -Request: -{ - "agentId": string, - "instances": number, - "model": string, - "gateway": "MCP" | "A2A" | "API" -} -``` - -#### 3.5 编排中心 - -##### POST /api/workflows/create -```typescript -Request: -{ - "name": string, - "description": string, - "gateway": "MCP" | "A2A" | "API", - "nodes": Array<{ - "agentId": string, - "agentType": "platform" | "custom", - "agentName": string, - "order": number - }> // 最多3个节点 -} - -Error (超过3节点): -{ - "success": false, - "error": { - "code": "WORKFLOW_NODE_LIMIT", - "message": "工作流最多支持3个Agent节点" - } -} -``` - -#### 3.6 计费与资源(新增余额充值) - -##### GET /api/billing/balance -```typescript -Response: -{ - "balance": number, // 当前余额 - "monthlySpent": number, // 本月消费 - "currency": "CNY" -} -``` - -##### POST /api/billing/recharge -```typescript -Request: -{ - "amount": number, // 充值金额 - "paymentMethod": "alipay" | "wechat" | "card" -} - -Response: -{ - "orderId": string, - "amount": number, - "paymentUrl": string, // 支付跳转URL - "status": "pending" -} -``` - -##### GET /api/billing/history -```typescript -Query: -{ - "startTime": string, // ISO 8601 精确到分钟 - "endTime": string, - "customerName"?: string, - "minCalls"?: number, - "maxCalls"?: number, - "export"?: "excel" | "csv" | "pdf", - "page": number, - "pageSize": number -} - -Response (查询): -{ - "total": number, - "records": Array<{ - "id": string, - "timestamp": string, // 精确到秒 - "agentName": string, - "duration": number, // 秒 - "eu": number, // 1 EU = 10秒 - "cost": number - }> -} - -Response (导出): -{ - "fileUrl": string, - "format": string, - "expiresAt": string -} -``` - -### 四、渠道合作伙伴API - -#### 4.1 租户管理 - -##### GET /api/channel/tenants -##### POST /api/channel/tenants/create - -##### PUT /api/channel/tenants/{id}/resources -分配资源(包含自定义Agent资源) -```typescript -Request: -{ - "agents": Array<{ - "agentId": string, - "quantity": number - }>, - "models": Array<{ - "modelName": string, - "rpm": number, - "tpm": number - }>, - "customAgentResources": { - "cpu": number, - "memory": number - } -} -``` - -##### PUT /api/channel/tenants/{id}/billing -管理租户计费 -```typescript -Request: -{ - "subscriptionTier": "free" | "pro" | "enterprise", - "discount": number // 0-100 -} -``` - -##### POST /api/channel/tenants/{id}/recharge(新增) -为租户充值 -```typescript -Request: -{ - "amount": number -} - -Response: -{ - "success": true, - "data": { - "tenantId": string, - "newBalance": number, - "rechargeAmount": number - } -} -``` - -##### PUT /api/channel/tenants/{id}/credit(新增) -设置租户授信额度 -```typescript -Request: -{ - "creditLimit": number -} - -Response: -{ - "success": true, - "data": { - "tenantId": string, - "creditLimit": number - } -} -``` - -#### 4.2 资源申请 - -##### POST /api/channel/resources/apply -```typescript -Request (模型申请): -{ - "type": "model", - "modelName": string, - "rpm": number, - "tpm": number, - "reason": string -} - -Request (Agent申请): -{ - "type": "agent", - "agentType": string, - "quantity": number, - "reason": string -} -``` - -#### 4.3 计费 - -##### GET /api/channel/billing/stats -```typescript -Query: -{ - "startTime": string, - "endTime": string, - "tenantName"?: string, - "minCalls"?: number, - "maxCalls"?: number, - "export"?: "excel" | "csv" | "pdf" -} - -Response: -{ - "tenantStats": Array<{ - "tenantId": string, - "tenantName": string, - "calls": number, - "totalEU": number, - "totalCost": number - }>, - "callRecords": Array<{ - "id": string, - "timestamp": string, - "tenantName": string, - "agentName": string, - "duration": number, - "eu": number, - "cost": number - }> -} -``` - -### 五、超级管理员API - -#### 5.1 渠道管理 - -##### PUT /api/admin/channels/{id}/resources(统一资源管理) -```typescript -Request: -{ - "models": Array, // 模型供应商ID - "agents": Array<{ - "agentId": string, - "quantity": number - }>, - "customAgentResources": { - "cpu": number, - "memory": number - }, - "channelCredit": number // 渠道授信额度 -} -``` - -##### GET /api/admin/channels/applications -获取渠道申请(模型+Agent) -```typescript -Response: -{ - "data": Array<{ - "id": string, - "channelId": string, - "channelName": string, - "type": "model" | "agent", - "details": { - "modelName"?: string, - "rpm"?: number, - "tpm"?: number, - "agentType"?: string, - "quantity"?: number - }, - "reason": string, - "status": "pending" | "approved" | "rejected", - "createdAt": string - }> -} -``` - -##### PUT /api/admin/channels/applications/{id}/review -```typescript -Request: -{ - "approved": boolean, - "reason"?: string -} -``` - -#### 5.2 计费(三维度) - -##### GET /api/admin/billing/overview -```typescript -Query: -{ - "startTime": string, - "endTime": string, - "channelName"?: string, - "tenantName"?: string, - "minCalls"?: number, - "maxCalls"?: number, - "export"?: "excel" | "csv" | "pdf" -} - -Response: -{ - "channelStats": Array<{ - "channelId": string, - "channelName": string, - "calls": number, - "totalEU": number, - "totalCost": number - }>, - "tenantStats": Array<{ - "tenantId": string, - "tenantName": string, - "channelName": string, - "calls": number, - "totalEU": number, - "totalCost": number - }>, - "callRecords": Array<{ - "id": string, - "timestamp": string, - "channelName": string, - "tenantName": string, - "agentName": string, - "duration": number, - "eu": number, - "cost": number - }> -} -``` - ---- - -## 数据库设计 - -### 核心表结构 - -```sql --- 用户表 -CREATE TABLE users ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name VARCHAR(100) NOT NULL, - email VARCHAR(255) UNIQUE NOT NULL, - password_hash VARCHAR(255) NOT NULL, - role VARCHAR(50) NOT NULL, -- user, channel_admin, super_admin, provider_admin - channel_id UUID REFERENCES channels(id), - subscription_tier VARCHAR(20) DEFAULT 'free', - discount DECIMAL(5,2) DEFAULT 0, - balance DECIMAL(12,2) DEFAULT 0, -- 账户余额 - credit_limit DECIMAL(12,2) DEFAULT 0, -- 授信额度 - status VARCHAR(20) DEFAULT 'active', - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- 渠道表 -CREATE TABLE channels ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name VARCHAR(100) NOT NULL, - email VARCHAR(255) UNIQUE NOT NULL, - password_hash VARCHAR(255) NOT NULL, - commission_rate DECIMAL(5,2) DEFAULT 0, - channel_credit DECIMAL(12,2) DEFAULT 0, -- 渠道授信额度 - custom_agent_cpu DECIMAL(5,2) DEFAULT 2, -- 自定义Agent CPU - custom_agent_memory DECIMAL(5,2) DEFAULT 4, -- 自定义Agent 内存 - status VARCHAR(20) DEFAULT 'active', - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- Agent表 -CREATE TABLE agents ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name VARCHAR(100) NOT NULL, - type VARCHAR(20) NOT NULL, -- platform, custom - description TEXT, - category VARCHAR(50), - cpu DECIMAL(5,2) NOT NULL, - memory DECIMAL(5,2) NOT NULL, - max_instances INT DEFAULT 100, - status VARCHAR(20) DEFAULT 'active', - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- 模型供应商表 -CREATE TABLE model_providers ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name VARCHAR(100) NOT NULL, - provider VARCHAR(50) NOT NULL, -- openai, anthropic, azure, google, aws - api_url VARCHAR(500) NOT NULL, - api_key_encrypted TEXT NOT NULL, - supported_models JSONB NOT NULL, - rpm INT NOT NULL, - tpm INT NOT NULL, - status VARCHAR(20) DEFAULT 'active', - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- 资源分配表 -CREATE TABLE resource_allocations ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - target_id UUID NOT NULL, - target_type VARCHAR(20) NOT NULL, -- channel, tenant - resource_type VARCHAR(20) NOT NULL, -- agent, model - resource_id UUID NOT NULL, - quantity INT, -- Agent数量 - rpm INT, -- 模型RPM - tpm INT, -- 模型TPM - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- 计费记录表 -CREATE TABLE billing_records ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - timestamp TIMESTAMP NOT NULL, - channel_id UUID REFERENCES channels(id), - tenant_id UUID REFERENCES users(id), - agent_id UUID REFERENCES agents(id), - agent_name VARCHAR(100) NOT NULL, - duration INT NOT NULL, -- 秒 - eu INT NOT NULL, -- 1 EU = 10秒 - cost DECIMAL(12,4) NOT NULL, - created_at TIMESTAMP DEFAULT NOW() -); - --- 充值记录表 -CREATE TABLE recharge_records ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES users(id), - channel_id UUID REFERENCES channels(id), - amount DECIMAL(12,2) NOT NULL, - payment_method VARCHAR(50), - status VARCHAR(20) DEFAULT 'pending', -- pending, success, failed - order_id VARCHAR(100), - created_at TIMESTAMP DEFAULT NOW(), - completed_at TIMESTAMP -); - --- 申请审批表 -CREATE TABLE applications ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID REFERENCES channels(id), - type VARCHAR(20) NOT NULL, -- model, agent - model_name VARCHAR(100), - rpm INT, - tpm INT, - agent_type VARCHAR(100), - quantity INT, - reason TEXT, - status VARCHAR(20) DEFAULT 'pending', -- pending, approved, rejected - reviewed_by UUID, - review_reason TEXT, - created_at TIMESTAMP DEFAULT NOW(), - reviewed_at TIMESTAMP -); - --- 工作流表 -CREATE TABLE workflows ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES users(id), - name VARCHAR(100) NOT NULL, - description TEXT, - gateway VARCHAR(20) NOT NULL, -- MCP, A2A, API - nodes JSONB NOT NULL, -- 最多3个节点 - status VARCHAR(20) DEFAULT 'active', - created_at TIMESTAMP DEFAULT NOW(), - updated_at TIMESTAMP DEFAULT NOW() -); - --- API密钥表 -CREATE TABLE api_keys ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES users(id), - api_key_hash VARCHAR(255) NOT NULL, - api_key_prefix VARCHAR(10) NOT NULL, -- sk-xxxx - last_used TIMESTAMP, - created_at TIMESTAMP DEFAULT NOW() -); - --- 索引 -CREATE INDEX idx_billing_timestamp ON billing_records(timestamp); -CREATE INDEX idx_billing_channel ON billing_records(channel_id); -CREATE INDEX idx_billing_tenant ON billing_records(tenant_id); -CREATE INDEX idx_applications_status ON applications(status); -CREATE INDEX idx_users_channel ON users(channel_id); -``` - ---- - -## 业务规则 - -### 1. EU计算规则 -``` -1 EU = 10秒调用时间 -EU = CEILING(duration_seconds / 10) -不足10秒按1 EU计算 -``` - -### 2. 计费价格(建议) -``` -1 EU = ¥0.01 (可配置) -``` - -### 3. 余额与授信 -``` -可用额度 = 账户余额 + 授信额度 -消费优先扣除余额,余额不足时使用授信额度 -授信额度用完后服务暂停 -``` - -### 4. 资源分配层级 -``` -超级管理员 → 渠道 → 租户 -每层只能分配不超过上级分配的资源 -``` - -### 5. 工作流限制 -``` -最多3个Agent节点 -支持平台Agent + 自定义Agent混合 -``` - -### 6. 平台Agent资源(固定) -``` -CPU: 2核/实例 -内存: 4GB/实例 -``` - -### 7. 自定义Agent资源(由上级分配) -``` -CPU: 由渠道/管理员配置 -内存: 由渠道/管理员配置 -``` - ---- - -## 认证与权限 - -### JWT Token结构 -```typescript -{ - "userId": string, - "role": "user" | "channel_admin" | "billing_admin" | "operations_admin" | "admin" | "super_admin" | "provider_admin", - "channelId"?: string, - "permissions": string[], - "iat": number, - "exp": number -} -``` - -### 权限列表 -| 权限 | 说明 | -|------|------| -| view:overview | 查看概览 | -| manage:tenants | 管理租户 | -| manage:resources | 管理资源 | -| view:billing | 查看计费 | -| manage:billing | 管理计费(含充值) | -| manage:settings | 管理设置 | -| approve:applications | 审批申请 | -| manage:channels | 管理渠道 | -| manage:providers | 管理供应商 | -| view:monitoring | 查看监控 | - -### 角色权限映射 -| 角色 | 说明 | 权限 | -|------|------|------| -| 计费管理员 (billing_admin) | 负责计费、充值等财务操作 | view:overview, view:billing, manage:billing | -| 运营管理员 (operations_admin) | 负责租户和资源的日常运营管理 | view:overview, manage:tenants, manage:resources, view:billing | -| 管理员 (admin) | 平台管理员,拥有除超级管理员外的大部分权限 | view:overview, manage:tenants, manage:resources, view:billing, manage:billing, manage:settings, view:monitoring | -| 超级管理员 (super_admin) | 拥有全部权限,可进行所有管理操作 | 全部权限 | - ---- - -## 部署要求 - -### 环境变量 -```bash -# 数据库 -DATABASE_URL=postgresql://taiji:By%40123456.@taijipda.postgres.database.azure.com:5432/postgres?sslmode=require - -# Redis -REDIS_URL=rediss://:nkJgt1ERFpdeYrEFNyFtsc5K4ycvx2jIeAzCaGGf1OQ%3D@taiji.southeastasia.redis.azure.net:10000/0?ssl_cert_reqs=none - -# JWT -JWT_SECRET=zsbgnw -JWT_EXPIRES_IN=24h - -# 加密 -ENCRYPTION_KEY=zsbgnw - -# 支付(可选) -ALIPAY_APP_ID=xxx -WECHAT_PAY_APP_ID=xxx - -# 云存储 -AWS_ACCESS_KEY_ID=xxx -AWS_SECRET_ACCESS_KEY=xxx -S3_BUCKET=taiji-ai-exports -``` - -### 服务依赖 -- PostgreSQL 14+ -- Redis 6+ -- Node.js 18+ (或 Python 3.10+) -- S3兼容存储(导出文件) - ---- - -## 开发优先级建议 - -### P0 - 核心功能 -1. 认证系统(登录、JWT、权限) -2. 用户/渠道/租户CRUD -3. 余额与授信管理 -4. 计费记录与查询 - -### P1 - 资源管理 -5. 资源分配逻辑 -6. 申请审批流程 -7. Agent部署管理 - -### P2 - 高级功能 -8. 服务网关集成(MCP/A2A/API) -9. 工作流引擎 -10. 监控与告警 - -### P3 - 运营支持 -11. 导出功能(Excel/CSV/PDF) -12. API密钥管理 -13. 数据模板处理 - ---- - -**文档版本**: v3.0 -**最后更新**: 2025-01-08 -**前端状态**: 设计完成,支持中英文 -**后端状态**: 待开发 diff --git a/BACKEND_VERIFICATION.md b/BACKEND_VERIFICATION.md deleted file mode 100644 index 40e9612..0000000 --- a/BACKEND_VERIFICATION.md +++ /dev/null @@ -1,621 +0,0 @@ -# 后端实现验证清单 - -本文档提供了一个系统的验证清单,帮助您确认所有后端功能都已正确实现并可以正常工作。 - -## 准备工作 - -### 环境配置 - -- [ ] Python 3.11+ 已安装 -- [ ] Docker 已安装 -- [ ] kubectl 已安装 -- [ ] Azure CLI 已安装 -- [ ] 已配置Azure订阅 - -### 数据库初始化 - -```bash -# 进入mcp-server目录 -cd services/mcp-server - -# 安装依赖 -pip install -r requirements.txt - -# 初始化数据库(会自动创建表和初始数据) -python -c "from database import init_db; import asyncio; asyncio.run(init_db())" -``` - -## 功能验证 - -### ✅ 1. 数据库模型验证 - -检查所有表是否正确创建: - -```sql --- 连接到PostgreSQL -psql "postgresql://taiji:By%40123456.@taijipda.postgres.database.azure.com:5432/postgres?sslmode=require" - --- 检查表 -\dt - --- 应该看到以下表: --- users --- channels --- agents --- model_providers --- resource_allocations --- billing_records --- recharge_records --- applications --- workflows --- api_keys --- gateway_apis --- data_templates --- tools --- sessions --- executions --- audit_logs -``` - -验证表结构: - -```sql --- 检查User表 -\d users - --- 验证余额和授信字段存在 -SELECT id, name, email, balance, credit_limit, subscription_tier FROM users LIMIT 1; - --- 检查Channel表 -\d channels - --- 检查Agent表 -\d agents - --- 检查计费记录表 -\d billing_records -``` - -### ✅ 2. 认证系统验证 - -启动服务器: - -```bash -cd services/mcp-server -python main.py -``` - -测试登录(用户): - -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "admin@taiji-ai.com", - "password": "admin123", - "role": "user" - }' -``` - -预期响应: -```json -{ - "success": true, - "data": { - "token": "eyJ...", - "refreshToken": "eyJ...", - "user": { - "id": "...", - "name": "系统管理员", - "email": "admin@taiji-ai.com", - "role": "super_admin" - } - } -} -``` - -测试API密钥: - -```bash -# 使用上面获取的token -TOKEN="your-token-here" - -curl -X GET http://localhost:8000/api/auth/keys/info \ - -H "Authorization: Bearer $TOKEN" -``` - -### ✅ 3. 用户侧平台API验证 - -测试仪表板统计: - -```bash -curl -X GET http://localhost:8000/api/user/dashboard/stats \ - -H "Authorization: Bearer $TOKEN" -``` - -预期响应: -```json -{ - "success": true, - "data": { - "activeAgents": 0, - "totalRequests": 0, - "euBalance": 0, - "systemHealth": 98.5 - } -} -``` - -测试创建工作流(验证3节点限制): - -```bash -# 测试4个节点(应该失败) -curl -X POST http://localhost:8000/api/user/workflows/create \ - -H "Authorization: Bearer $TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "测试工作流", - "description": "测试节点限制", - "gateway": "MCP", - "nodes": [ - {"agentId": "1", "agentType": "platform", "agentName": "Agent1", "order": 1}, - {"agentId": "2", "agentType": "platform", "agentName": "Agent2", "order": 2}, - {"agentId": "3", "agentType": "platform", "agentName": "Agent3", "order": 3}, - {"agentId": "4", "agentType": "platform", "agentName": "Agent4", "order": 4} - ] - }' -``` - -预期响应: -```json -{ - "success": false, - "error": { - "code": "VALIDATION_ERROR", - "message": "工作流最多支持3个Agent节点" - } -} -``` - -测试余额查询: - -```bash -curl -X GET http://localhost:8000/api/user/billing/balance \ - -H "Authorization: Bearer $TOKEN" -``` - -### ✅ 4. 渠道合作伙伴API验证 - -创建测试渠道: - -```bash -# 使用管理员账号 -curl -X POST http://localhost:8000/api/admin/channels/create \ - -H "Authorization: Bearer $ADMIN_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "测试渠道", - "email": "channel@test.com", - "password": "test123", - "commissionRate": 10 - }' -``` - -渠道登录: - -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "channel@test.com", - "password": "test123", - "role": "channel" - }' -``` - -创建租户: - -```bash -curl -X POST http://localhost:8000/api/channel/tenants/create \ - -H "Authorization: Bearer $CHANNEL_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "测试租户", - "email": "tenant@test.com", - "password": "test123", - "subscriptionTier": "pro" - }' -``` - -为租户充值: - -```bash -curl -X POST http://localhost:8000/api/channel/tenants/{tenant_id}/recharge \ - -H "Authorization: Bearer $CHANNEL_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "amount": 100 - }' -``` - -设置授信额度: - -```bash -curl -X PUT http://localhost:8000/api/channel/tenants/{tenant_id}/credit \ - -H "Authorization: Bearer $CHANNEL_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "creditLimit": 500 - }' -``` - -### ✅ 5. 超级管理员API验证 - -获取平台统计: - -```bash -curl -X GET http://localhost:8000/api/admin/dashboard/stats \ - -H "Authorization: Bearer $ADMIN_TOKEN" -``` - -查看所有渠道: - -```bash -curl -X GET http://localhost:8000/api/admin/channels \ - -H "Authorization: Bearer $ADMIN_TOKEN" -``` - -分配渠道资源: - -```bash -curl -X PUT http://localhost:8000/api/admin/channels/{channel_id}/resources \ - -H "Authorization: Bearer $ADMIN_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "models": ["model-id-1"], - "agents": [ - {"agentId": "agent-id-1", "quantity": 10} - ], - "customAgentResources": { - "cpu": 4, - "memory": 8 - }, - "channelCredit": 10000 - }' -``` - -查看申请列表: - -```bash -curl -X GET http://localhost:8000/api/admin/channels/applications \ - -H "Authorization: Bearer $ADMIN_TOKEN" -``` - -审批申请: - -```bash -curl -X PUT http://localhost:8000/api/admin/channels/applications/{app_id}/review \ - -H "Authorization: Bearer $ADMIN_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "approved": true, - "reason": "审批通过" - }' -``` - -### ✅ 6. 供应商管理API验证 - -创建模型供应商: - -```bash -curl -X POST http://localhost:8000/api/providers/models/create \ - -H "Authorization: Bearer $ADMIN_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "OpenAI", - "provider": "openai", - "apiUrl": "https://api.openai.com/v1", - "apiKey": "sk-xxxxx", - "supportedModels": ["gpt-4", "gpt-3.5-turbo"], - "rpm": 3500, - "tpm": 90000 - }' -``` - -获取供应商列表: - -```bash -curl -X GET http://localhost:8000/api/providers/models \ - -H "Authorization: Bearer $ADMIN_TOKEN" -``` - -### ✅ 7. 计费功能验证 - -创建测试计费记录: - -```python -# Python脚本测试 -import asyncio -from database import AsyncSessionLocal -from app.billing import create_billing_record - -async def test_billing(): - async with AsyncSessionLocal() as db: - # 创建计费记录(60秒 = 6 EU = ¥0.06) - record = await create_billing_record( - tenant_id="tenant-uuid", - agent_id="agent-uuid", - agent_name="测试Agent", - duration_seconds=60, - db=db, - channel_id="channel-uuid" - ) - - print(f"EU: {record.eu}") # 应该是6 - print(f"成本: {record.cost}") # 应该是0.06 - -asyncio.run(test_billing()) -``` - -验证EU计算: - -```python -from app.billing import calculate_eu, calculate_cost - -# 测试EU计算 -assert calculate_eu(5) == 1 # 不足10秒按1 EU -assert calculate_eu(10) == 1 # 10秒 = 1 EU -assert calculate_eu(15) == 2 # 15秒 = 2 EU -assert calculate_eu(60) == 6 # 60秒 = 6 EU - -# 测试成本计算 -from decimal import Decimal -assert calculate_cost(1) == Decimal("0.01") -assert calculate_cost(100) == Decimal("1.00") - -print("✅ EU计算验证通过") -``` - -验证余额扣除: - -```python -from app.billing import deduct_balance, add_balance -from decimal import Decimal - -async def test_balance(): - async with AsyncSessionLocal() as db: - # 先充值 - success, msg = await add_balance("user-id", Decimal("100"), db) - print(f"充值: {success}, {msg}") - - # 扣费 - success, msg = await deduct_balance("user-id", Decimal("10"), db) - print(f"扣费: {success}, {msg}") - -asyncio.run(test_balance()) -``` - -### ✅ 8. Azure AKS部署验证 - -检查K8s配置文件: - -```bash -# 验证YAML语法 -kubectl apply --dry-run=client -f services/mcp-server/k8s/deployment.yaml -kubectl apply --dry-run=client -f services/mcp-server/k8s/ingress.yaml -``` - -构建Docker镜像: - -```bash -cd services/mcp-server -docker build -t mcp-server:test . - -# 测试镜像 -docker run -p 8000:8000 -e DATABASE_URL="sqlite+aiosqlite:///./test.db" mcp-server:test -``` - -测试健康检查: - -```bash -curl http://localhost:8000/health -``` - -预期响应: -```json -{ - "status": "healthy", - "database": "connected", - "timestamp": "2025-12-25T..." -} -``` - -## API文档验证 - -访问Swagger文档: - -``` -http://localhost:8000/docs -``` - -检查是否包含所有端点: -- [ ] /api/auth/* (6个端点) -- [ ] /api/user/* (12个端点) -- [ ] /api/channel/* (9个端点) -- [ ] /api/admin/* (11个端点) -- [ ] /api/providers/* (6个端点) - -## 性能测试 - -### 并发测试 - -```bash -# 安装ab (Apache Bench) -# Ubuntu: apt-get install apache2-utils -# macOS: 已预装 - -# 测试健康检查端点 -ab -n 1000 -c 10 http://localhost:8000/health - -# 测试认证端点 -ab -n 100 -c 5 -p login.json -T application/json http://localhost:8000/api/auth/login -``` - -### 数据库连接池测试 - -```python -import asyncio -from database import check_db_connection - -async def test_connections(): - tasks = [check_db_connection() for _ in range(20)] - results = await asyncio.gather(*tasks) - print(f"成功连接: {sum(results)}/20") - -asyncio.run(test_connections()) -``` - -## 安全验证 - -### 认证测试 - -测试未授权访问: - -```bash -# 应该返回401 -curl http://localhost:8000/api/user/dashboard/stats -``` - -测试错误的token: - -```bash -# 应该返回401 -curl -H "Authorization: Bearer invalid-token" \ - http://localhost:8000/api/user/dashboard/stats -``` - -### SQL注入测试 - -```bash -# 尝试SQL注入(应该被参数化查询阻止) -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "admin@taiji-ai.com\" OR \"1\"=\"1", - "password": "anything", - "role": "user" - }' -``` - -### 密码哈希验证 - -```python -from app.auth import get_password_hash, verify_password - -# 测试密码哈希 -password = "test123" -hashed = get_password_hash(password) -print(f"哈希长度: {len(hashed)}") # 应该是60(bcrypt) - -# 验证密码 -assert verify_password(password, hashed) == True -assert verify_password("wrong", hashed) == False - -print("✅ 密码哈希验证通过") -``` - -## 日志验证 - -检查日志文件: - -```bash -tail -f logs/mcp-server.log -``` - -验证日志格式(应该是JSON): - -```json -{ - "timestamp": "2025-12-25T10:00:00Z", - "level": "INFO", - "message": "Application started", - "service": "mcp-server" -} -``` - -## 监控指标验证 - -访问Prometheus metrics: - -```bash -curl http://localhost:8000/metrics -``` - -应该看到: -- `http_requests_total` -- `http_request_duration_seconds` -- `database_connections` -- 等等 - -## 最终检查清单 - -### 代码质量 -- [ ] 所有文件无linter错误 -- [ ] 代码遵循PEP 8规范 -- [ ] 类型注解完整 -- [ ] 文档字符串完整 - -### 功能完整性 -- [ ] 所有API端点已实现 -- [ ] 所有业务规则已实现 -- [ ] 错误处理完善 -- [ ] 数据验证完整 - -### 数据库 -- [ ] 所有表已创建 -- [ ] 索引已添加 -- [ ] 关联关系正确 -- [ ] 初始数据已加载 - -### 安全性 -- [ ] JWT认证工作正常 -- [ ] API密钥认证工作正常 -- [ ] 密码正确哈希 -- [ ] 敏感数据已加密 -- [ ] CORS配置正确 - -### 性能 -- [ ] 数据库连接池配置 -- [ ] 查询性能优化 -- [ ] 缓存机制(如需要) -- [ ] 并发处理能力 - -### 部署 -- [ ] Docker镜像构建成功 -- [ ] K8s配置有效 -- [ ] 健康检查工作正常 -- [ ] 环境变量配置正确 -- [ ] Secrets已配置 - -### 文档 -- [ ] API文档完整 -- [ ] 部署文档清晰 -- [ ] README更新 -- [ ] 变更日志记录 - -## 问题反馈 - -如果在验证过程中发现任何问题,请记录: - -1. **问题描述**: -2. **重现步骤**: -3. **预期结果**: -4. **实际结果**: -5. **错误日志**: - ---- - -**验证完成日期**: _______________ -**验证人**: _______________ -**状态**: [ ] 通过 [ ] 未通过 - diff --git a/DOCS_UPDATE_SUMMARY.md b/DOCS_UPDATE_SUMMARY.md deleted file mode 100644 index 8968baf..0000000 --- a/DOCS_UPDATE_SUMMARY.md +++ /dev/null @@ -1,178 +0,0 @@ -# 文档更新总结 - -## 更新日期 -2025年12月25日 - -## 更新的文档 - -### 1. API接口文档 (Docs/前后端调试说明/API接口文档.md) - -**版本**: v1.3.0 → v2.0.0 - -**主要更新内容**: - -✅ **新增完整API章节** (约2000行新内容): -- 认证模块 API (6个端点) - - 登录、登出、刷新Token、修改密码、获取/重生成API密钥 -- 用户侧平台 API (14个端点) - - 概览、网关配置、工具生成、Agent部署、工作流编排、计费管理 -- 渠道合作伙伴 API (8个端点) - - 租户管理、资源分配、充值、授信额度、计费统计 -- 超级管理员 API (10个端点) - - 渠道管理、申请审批、资源管理、Agent监控、三维度计费 -- 供应商管理 API (6个端点) - - 模型供应商CRUD操作和连接测试 - -✅ **新增业务规则章节**: -- EU计算规则 (1 EU = 10秒) -- 计费价格 (1 EU = ¥0.01) -- 余额与授信机制 -- 资源分配层级 (三级结构) -- 工作流限制 (最多3节点) -- Agent资源配置规则 - -✅ **完善认证说明**: -- JWT Bearer Token认证详解 -- API Key认证详解 -- 豁免路径列表 -- 四种权限角色说明 -- 完整的认证示例 - -✅ **其他更新**: -- 端口变更:8002 → 8000 -- 统一响应格式说明 -- 完整的请求/响应示例 -- 错误处理说明 -- 相关文档链接 - -### 2. 项目工作流程文档 (Docs/项目文档/项目工作流程.md) - -**版本**: v1.0 → v2.0.0 - -**主要更新内容**: - -✅ **架构更新**: -- 端口变更说明 (8002 → 8000) -- 认证机制更新 (已启用JWT + API Key) -- 响应格式统一说明 - -✅ **核心数据流完善**: -- 认证与权限说明 -- EU计算和计费规则 -- 可用额度计算公式 -- 工作流限制说明 - -✅ **业务流程更新**: -- 新增认证流程章节 (4.0) -- 更新所有子系统的API路径 -- 添加新功能说明 (充值、授信、审批等) -- 标注已弃用的API - -✅ **快速联调脚本重写**: -- 所有脚本添加认证 (Bearer Token) -- 更新端口号到8000 -- 添加更多实用示例 -- 分类更清晰 (认证、用户、渠道、管理员、供应商) - -✅ **新增章节**: -- 重要变更说明 (v2.0.0) -- 弃用API列表 -- 完整的参考文档链接 - -## 文档特点 - -### API接口文档特点 -1. **完整性**: 覆盖所有44个API端点 -2. **详细性**: 每个API都有完整的请求/响应示例 -3. **实用性**: 提供可直接运行的curl命令 -4. **规范性**: 遵循OpenAPI规范 -5. **可维护性**: 清晰的章节结构和版本管理 - -### 工作流程文档特点 -1. **快速上手**: 5分钟了解整个系统 -2. **实战导向**: 提供大量可运行的脚本 -3. **角色明确**: 按照四种角色分类说明 -4. **变更透明**: 清楚标注版本变更和弃用内容 -5. **参考完整**: 链接到所有相关文档 - -## 文档之间的关联 - -``` -QUICK_START.md (快速开始) - ↓ -项目工作流程.md (整体流程和脚本) - ↓ -API接口文档.md (详细的API规范) - ↓ -BACKEND_REQUIREMENTS.md (需求文档) - ↓ -BACKEND_IMPLEMENTATION_SUMMARY.md (实现总结) - ↓ -BACKEND_VERIFICATION.md (验证清单) -``` - -## 使用建议 - -### 对于前端开发者 -1. 先读 `项目工作流程.md` 了解整体架构 -2. 再读 `API接口文档.md` 了解具体接口 -3. 使用 `QUICK_START.md` 快速启动服务 -4. 参考工作流程中的curl示例进行联调 - -### 对于后端开发者 -1. 先读 `BACKEND_REQUIREMENTS.md` 了解需求 -2. 再读 `BACKEND_IMPLEMENTATION_SUMMARY.md` 了解实现 -3. 使用 `BACKEND_VERIFICATION.md` 验证功能 -4. 参考 `API接口文档.md` 确认接口规范 - -### 对于QA测试人员 -1. 使用 `项目工作流程.md` 中的脚本进行功能测试 -2. 使用 `BACKEND_VERIFICATION.md` 进行系统验证 -3. 参考 `API接口文档.md` 编写测试用例 - -### 对于产品经理 -1. 阅读 `BACKEND_REQUIREMENTS.md` 了解功能范围 -2. 阅读 `项目工作流程.md` 了解业务流程 -3. 参考 `API接口文档.md` 的业务规则章节 - -## 下一步计划 - -### 短期 (1-2周) -- [ ] 添加API性能基准测试结果 -- [ ] 补充错误码完整列表 -- [ ] 添加更多业务场景示例 -- [ ] 完善WebSocket API文档 - -### 中期 (1个月) -- [ ] 添加API变更历史详细记录 -- [ ] 创建Postman/Insomnia集合 -- [ ] 编写自动化测试文档 -- [ ] 添加监控指标说明 - -### 长期 (持续) -- [ ] 保持文档与代码同步 -- [ ] 收集用户反馈改进文档 -- [ ] 添加最佳实践指南 -- [ ] 创建故障排查手册 - -## 文档维护规范 - -1. **版本管理**: 采用语义化版本号 (major.minor.patch) -2. **更新日志**: 每次更新都记录在更新日志章节 -3. **示例更新**: 确保所有示例都能实际运行 -4. **交叉引用**: 保持文档间链接的准确性 -5. **定期审查**: 每个月审查一次文档准确性 - -## 联系方式 - -如有文档相关问题或建议: -- Email: admin@taiji-ai.com -- 项目Wiki: (待添加) -- Issue Tracker: (待添加) - ---- - -**文档维护者**: taiji-AI-PAD 项目组 -**最后更新**: 2025年12月25日 -**文档状态**: ✅ 完成并验证 - diff --git a/Docs/前端开发/前端角色权限控制指南.md b/Docs/前端开发/前端角色权限控制指南.md index 96df0ce..3690ff6 100644 --- a/Docs/前端开发/前端角色权限控制指南.md +++ b/Docs/前端开发/前端角色权限控制指南.md @@ -887,3 +887,4 @@ A: 清除本地存储,跳转到登录页,要求用户重新登录。 **最后更新**: 2025-12-25 **维护人**: Taiji AI-PAD Team + diff --git a/NEW_ADMIN_ACCOUNT.md b/NEW_ADMIN_ACCOUNT.md deleted file mode 100644 index 929b13d..0000000 --- a/NEW_ADMIN_ACCOUNT.md +++ /dev/null @@ -1,261 +0,0 @@ -# 新增管理员账号说明 - -## 账号信息 - -- **用户名**: xiaohei -- **邮箱**: xiaohei@test.com -- **密码**: 1233456 -- **角色**: admin(管理员) -- **订阅等级**: enterprise -- **账户余额**: ¥5,000 -- **授信额度**: ¥20,000 -- **状态**: active - -## 权限说明 - -作为**管理员**角色,xiaohei账号拥有以下权限: - -| 权限 | 说明 | -|------|------| -| view:overview | 查看概览 | -| manage:tenants | 管理租户 | -| manage:resources | 管理资源 | -| view:billing | 查看计费 | -| manage:billing | 管理计费(含充值) | -| manage:settings | 管理设置 | -| view:monitoring | 查看监控 | - -**注意**: 管理员角色拥有除超级管理员外的大部分权限,可以进行租户管理、资源管理、计费管理、系统设置等操作。 - -## 创建方法 - -### 方法1: 使用初始化脚本(推荐) - -运行测试账号初始化脚本会自动创建此账号: - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server -python scripts/init_test_accounts.py -``` - -脚本会输出所有创建的账号信息,包括xiaohei账号。 - -### 方法2: 手动创建 - -如果需要单独创建此账号,可以使用以下SQL或API: - -#### 使用API创建(需要超级管理员权限) - -```bash -# 先登录获取超级管理员token -TOKEN=$(curl -s -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "superadmin@test.com", - "password": "super123", - "role": "super_admin" - }' | jq -r '.data.token') - -# 创建xiaohei账号 -curl -X POST http://localhost:8000/api/admin/users \ - -H "Authorization: Bearer $TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "xiaohei", - "email": "xiaohei@test.com", - "password": "1233456", - "role": "admin", - "subscription_tier": "enterprise", - "balance": 5000.0, - "credit_limit": 20000.0 - }' -``` - -## 登录测试 - -### 使用curl测试登录 - -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "xiaohei@test.com", - "password": "1233456", - "role": "admin" - }' -``` - -**预期响应**: -```json -{ - "success": true, - "data": { - "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", - "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", - "user": { - "id": "uuid", - "name": "xiaohei", - "email": "xiaohei@test.com", - "role": "admin", - "permissions": [ - "view:overview", - "manage:tenants", - "manage:resources", - "view:billing", - "manage:billing", - "manage:settings", - "view:monitoring" - ] - } - } -} -``` - -### 使用前端登录 - -1. 打开登录页面 -2. 选择角色:**管理员** -3. 输入邮箱:`xiaohei@test.com` -4. 输入密码:`1233456` -5. 点击登录 - -登录成功后会自动跳转到管理员仪表板。 - -## 可访问的功能模块 - -xiaohei作为管理员,可以访问以下功能模块: - -### 1. 仪表板 -- ✅ 查看系统概览 -- ✅ 查看关键指标统计 -- ✅ 查看系统监控数据 - -### 2. 租户管理 -- ✅ 查看租户列表 -- ✅ 创建新租户 -- ✅ 编辑租户信息 -- ✅ 停用/激活租户 -- ✅ 查看租户资源使用情况 - -### 3. 资源管理 -- ✅ 查看资源分配情况 -- ✅ 调整资源配额 -- ✅ 查看资源使用统计 -- ✅ 管理Agent资源 - -### 4. 计费管理 -- ✅ 查看计费记录 -- ✅ 执行充值操作 -- ✅ 查看账单统计 -- ✅ 导出计费报表 - -### 5. 系统设置 -- ✅ 修改系统配置 -- ✅ 管理系统参数 -- ✅ 配置通知设置 - -### 6. 监控管理 -- ✅ 查看系统监控 -- ✅ 查看性能指标 -- ✅ 查看日志 - -### ❌ 不能访问的功能 - -- ❌ 渠道管理(需要超级管理员权限) -- ❌ 供应商管理(需要供应商管理员权限) -- ❌ 修改超级管理员权限 -- ❌ 删除超级管理员账号 - -## 安全注意事项 - -1. **密码安全**: - - 当前密码为测试密码(1233456) - - 生产环境请立即修改为强密码 - - 建议密码长度至少12位,包含大小写字母、数字和特殊字符 - -2. **权限控制**: - - 管理员权限较高,请谨慎操作 - - 所有操作都会记录审计日志 - - 建议定期审查账号的操作记录 - -3. **账号管理**: - - 定期更换密码 - - 不要与他人共享账号 - - 发现异常立即禁用账号 - -## 测试建议 - -### 1. 功能测试 -```bash -# 获取token -TOKEN=$(curl -s -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "xiaohei@test.com", - "password": "1233456", - "role": "admin" - }' | jq -r '.data.token') - -# 测试查看仪表板 -curl -X GET http://localhost:8000/api/admin/dashboard/stats \ - -H "Authorization: Bearer $TOKEN" - -# 测试查看租户列表 -curl -X GET http://localhost:8000/api/admin/tenants \ - -H "Authorization: Bearer $TOKEN" - -# 测试查看计费记录 -curl -X GET http://localhost:8000/api/admin/billing/records \ - -H "Authorization: Bearer $TOKEN" -``` - -### 2. 权限测试 -```bash -# 应该能访问的端点(返回200) -curl -X GET http://localhost:8000/api/admin/tenants -H "Authorization: Bearer $TOKEN" -curl -X GET http://localhost:8000/api/admin/resources -H "Authorization: Bearer $TOKEN" -curl -X GET http://localhost:8000/api/admin/billing/records -H "Authorization: Bearer $TOKEN" - -# 不应该能访问的端点(返回403) -curl -X GET http://localhost:8000/api/admin/channels -H "Authorization: Bearer $TOKEN" -``` - -## 常见问题 - -### Q1: 登录失败怎么办? -A: 请检查: -- 邮箱是否正确:xiaohei@test.com -- 密码是否正确:1233456 -- 角色是否选择:admin -- 账号是否已创建(运行初始化脚本) - -### Q2: 提示权限不足? -A: 管理员角色不能访问以下功能: -- 渠道管理(需要超级管理员) -- 供应商管理(需要供应商管理员) -如需这些权限,请联系超级管理员。 - -### Q3: 如何修改密码? -A: 登录后调用密码修改API: -```bash -curl -X POST http://localhost:8000/api/auth/change-password \ - -H "Authorization: Bearer $TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "old_password": "1233456", - "new_password": "your_new_strong_password" - }' -``` - -## 更新记录 - -| 日期 | 操作 | 说明 | -|------|------|------| -| 2025-12-25 | 创建 | 新增管理员账号xiaohei | - ---- - -**创建日期**: 2025-12-25 -**账号状态**: ✅ 已创建 -**测试状态**: ⬜ 待测试 - diff --git a/PERMISSIONS_IMPLEMENTATION_COMPLETE.md b/PERMISSIONS_IMPLEMENTATION_COMPLETE.md deleted file mode 100644 index 60011d7..0000000 --- a/PERMISSIONS_IMPLEMENTATION_COMPLETE.md +++ /dev/null @@ -1,500 +0,0 @@ -# 权限系统实施完成报告 - -## 文档信息 -- **项目名称**: Taiji AI-PAD -- **模块**: 权限系统 -- **版本**: 1.0 -- **完成日期**: 2025-12-25 -- **状态**: ✅ 已完成 - ---- - -## 执行摘要 - -根据用户需求,已成功完成权限系统的更新和完善,包括: -1. ✅ 更新权限设计,支持4种管理员角色 -2. ✅ 创建数据库测试账号初始化脚本 -3. ✅ 编写前端角色选择和权限控制指南 -4. ✅ 编写完整的权限API测试用例 -5. ✅ 编写pytest单元测试和集成测试 - ---- - -## 一、权限设计更新 - -### 1.1 角色体系(7种角色) - -| 角色代码 | 角色名称 | 说明 | 权限范围 | -|---------|---------|------|---------| -| `user` | 租户用户 | 普通用户 | 查看自己的资源和账单 | -| `channel_admin` | 渠道管理员 | 管理渠道 | 租户管理、资源分配、计费管理 | -| `billing_admin` | **计费管理员** | 财务操作 | 查看和管理计费、充值 | -| `operations_admin` | **运营管理员** | 运营管理 | 租户管理、资源管理、查看计费 | -| `admin` | **管理员** | 平台管理 | 综合管理权限(除超级管理员权限外) | -| `super_admin` | **超级管理员** | 最高权限 | 全部权限 | -| `provider_admin` | 供应商管理员 | 供应商管理 | 模型管理 | - -### 1.2 权限列表(10种权限) - -``` -view:overview - 查看概览 -manage:tenants - 管理租户 -manage:resources - 管理资源 -view:billing - 查看计费 -manage:billing - 管理计费(含充值) -manage:settings - 管理设置 -approve:applications - 审批申请 -manage:channels - 管理渠道 -manage:providers - 管理供应商 -view:monitoring - 查看监控 -``` - -### 1.3 更新的文件 - -#### 后端代码 -- ✅ `services/mcp-server/models.py` - 更新User模型角色字段 -- ✅ `services/mcp-server/app/permissions.py` - **新建**权限管理模块 -- ✅ `services/mcp-server/app/schemas.py` - 更新登录Schema -- ✅ `services/mcp-server/app/routes/auth.py` - 优化登录逻辑 - -#### 文档 -- ✅ `BACKEND_REQUIREMENTS.md` - 更新权限设计章节 -- ✅ `Docs/前后端调试说明/API接口文档.md` - 更新角色说明 -- ✅ `Docs/项目文档/项目工作流程.md` - 更新认证与权限说明 -- ✅ `PERMISSIONS_UPDATE_SUMMARY.md` - **新建**权限更新说明 - ---- - -## 二、数据库测试账号 - -### 2.1 初始化脚本 - -**文件**: `services/mcp-server/scripts/init_test_accounts.py` - -**功能**: -- 创建2个测试渠道 -- 创建11个测试用户(覆盖所有角色) -- 创建3个测试供应商 -- 为部分用户创建API密钥 - -### 2.2 测试账号列表 - -| 角色 | 邮箱 | 密码 | 余额 | 授信额度 | -|------|------|------|------|---------| -| 超级管理员 | superadmin@test.com | super123 | ¥10,000 | ¥50,000 | -| 管理员 | admin@test.com | admin123 | ¥5,000 | ¥20,000 | -| 管理员xiaohei | xiaohei@test.com | 1233456 | ¥5,000 | ¥20,000 | -| 计费管理员 | billing@test.com | billing123 | ¥1,000 | ¥5,000 | -| 运营管理员 | operations@test.com | ops123 | ¥1,000 | ¥5,000 | -| 渠道管理员A | channel-admin-a@test.com | channel123 | ¥3,000 | ¥10,000 | -| 渠道管理员B | channel-admin-b@test.com | channel123 | ¥2,000 | ¥8,000 | -| 供应商管理员 | provider@test.com | provider123 | ¥1,000 | ¥5,000 | -| 测试用户1 | user1@test.com | user123 | ¥100 | ¥500 | -| 测试用户2 | user2@test.com | user123 | ¥500 | ¥2,000 | -| 测试用户3 | user3@test.com | user123 | ¥50 | ¥200 | - -### 2.3 使用方法 - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server -python scripts/init_test_accounts.py -``` - -**输出**: -- 创建的账号列表 -- API密钥(如果生成) -- 测试登录命令 - ---- - -## 三、前端角色权限控制指南 - -### 3.1 指南文档 - -**文件**: `Docs/前端开发/前端角色权限控制指南.md` - -**内容**: -1. 角色体系概述 -2. 登录界面实现(含React示例代码) -3. 权限控制实现(权限工具函数) -4. 路由守卫(RoleRoute组件) -5. UI组件权限控制(PermissionWrapper组件) -6. API调用权限(Axios拦截器) -7. 完整示例代码 - -### 3.2 核心组件 - -#### 登录页面 -```tsx - -- 支持7种角色选择 -- 邮箱/密码登录 -- 根据角色自动跳转 -``` - -#### 路由守卫 -```tsx - - - -``` - -#### 权限包装 -```tsx - - - -``` - -### 3.3 工具函数 - -```typescript -hasPermission(permission) // 检查单个权限 -hasAnyPermission(permissions) // 检查任意权限 -hasAllPermissions(permissions) // 检查所有权限 -hasRole(role) // 检查角色 -isAdmin() // 是否是管理员 -isSuperAdmin() // 是否是超级管理员 -``` - ---- - -## 四、权限测试用例 - -### 4.1 测试文件 - -#### 配置文件 -- ✅ `services/mcp-server/tests/__init__.py` - 测试模块初始化 -- ✅ `services/mcp-server/tests/conftest.py` - Pytest配置和fixtures -- ✅ `services/mcp-server/pytest.ini` - Pytest配置文件 -- ✅ `services/mcp-server/requirements-test.txt` - 测试依赖 - -#### 测试用例 -- ✅ `services/mcp-server/tests/test_permissions.py` - 权限系统测试(8个测试类) -- ✅ `services/mcp-server/tests/test_api_endpoints.py` - API端点测试(7个测试类) - -### 4.2 测试覆盖 - -#### test_permissions.py(权限系统测试) - -| 测试类 | 测试用例数 | 说明 | -|--------|----------|------| -| TestPermissions | 2 | 权限映射和检查函数 | -| TestAuthenticationAPI | 4 | 登录、密码、角色验证 | -| TestRoleBasedAccess | 4 | 基于角色的访问控制 | -| TestAPIKeyAuthentication | 2 | API密钥认证 | -| TestTokenRefresh | 1 | Token刷新 | -| TestPasswordChange | 2 | 密码修改 | -| TestLogout | 1 | 登出 | -| TestCrossRoleAccess | 1 | 跨角色访问控制 | -| TestPermissionInheritance | 3 | 权限继承 | -| **总计** | **20** | | - -#### test_api_endpoints.py(API端点测试) - -| 测试类 | 测试用例数 | 说明 | -|--------|----------|------| -| TestUserAPIs | 3 | 用户端API | -| TestChannelAPIs | 2 | 渠道端API | -| TestAdminAPIs | 2 | 管理员API | -| TestBillingAdminAPIs | 3 | 计费管理员API | -| TestOperationsAdminAPIs | 3 | 运营管理员API | -| TestProviderAPIs | 2 | 供应商API | -| TestHealthCheck | 1 | 健康检查 | -| **总计** | **16** | | - -**总测试用例数**: **36个** - -### 4.3 测试运行 - -#### 运行脚本 -```bash -# 使用测试脚本 -./scripts/run_tests.sh all # 运行所有测试 -./scripts/run_tests.sh permissions # 只运行权限测试 -./scripts/run_tests.sh api # 只运行API测试 -./scripts/run_tests.sh coverage # 生成覆盖率报告 -./scripts/run_tests.sh quick # 快速测试 -``` - -#### 直接使用pytest -```bash -pytest tests/ -v # 运行所有测试 -pytest tests/test_permissions.py -v # 运行权限测试 -pytest tests/ --cov=app --cov=models # 生成覆盖率 -``` - -### 4.4 测试fixtures - -```python -test_engine # 测试数据库引擎 -test_session # 测试数据库会话 -test_app # 测试FastAPI应用 -client # 测试HTTP客户端 -test_channel # 测试渠道 -test_users # 测试用户(所有角色) -auth_tokens # 认证tokens(所有角色) -auth_headers # 认证头生成函数 -``` - ---- - -## 五、测试指南文档 - -### 5.1 文档 - -**文件**: `TESTING_GUIDE.md` - -**内容**: -1. 测试概述 -2. 环境准备 -3. 运行测试(3种方法) -4. 测试用例说明(详细) -5. 测试账号 -6. 手动测试(curl命令) -7. CI/CD集成(GitHub Actions、GitLab CI) -8. 测试最佳实践 -9. 常见问题 - -### 5.2 测试脚本 - -**文件**: `services/mcp-server/scripts/run_tests.sh` - -**功能**: -- 自动安装测试依赖 -- 支持5种测试模式 -- 生成覆盖率报告 -- 友好的命令行界面 - ---- - -## 六、项目结构 - -``` -taiji-AI-PAD/ -├── services/ -│ └── mcp-server/ -│ ├── app/ -│ │ ├── permissions.py # ✅ 新建 - 权限管理模块 -│ │ ├── schemas.py # ✅ 更新 - 支持新角色 -│ │ └── routes/ -│ │ └── auth.py # ✅ 更新 - 优化登录逻辑 -│ ├── models.py # ✅ 更新 - User模型 -│ ├── tests/ # ✅ 新建 - 测试目录 -│ │ ├── __init__.py -│ │ ├── conftest.py # Pytest配置 -│ │ ├── test_permissions.py # 权限测试 -│ │ └── test_api_endpoints.py # API测试 -│ ├── scripts/ -│ │ ├── init_test_accounts.py # ✅ 新建 - 测试账号初始化 -│ │ └── run_tests.sh # ✅ 新建 - 测试运行脚本 -│ ├── pytest.ini # ✅ 新建 - Pytest配置 -│ └── requirements-test.txt # ✅ 新建 - 测试依赖 -├── Docs/ -│ ├── 前端开发/ -│ │ └── 前端角色权限控制指南.md # ✅ 新建 -│ ├── 前后端调试说明/ -│ │ └── API接口文档.md # ✅ 更新 - 角色说明 -│ └── 项目文档/ -│ └── 项目工作流程.md # ✅ 更新 - 权限说明 -├── BACKEND_REQUIREMENTS.md # ✅ 更新 - 权限设计 -├── PERMISSIONS_UPDATE_SUMMARY.md # ✅ 新建 - 权限更新说明 -├── PERMISSIONS_IMPLEMENTATION_COMPLETE.md # ✅ 新建 - 本文档 -└── TESTING_GUIDE.md # ✅ 新建 - 测试指南 -``` - ---- - -## 七、交付成果 - -### 7.1 代码交付 - -#### 后端代码(5个文件) -1. ✅ `services/mcp-server/models.py` - 更新 -2. ✅ `services/mcp-server/app/permissions.py` - 新建 -3. ✅ `services/mcp-server/app/schemas.py` - 更新 -4. ✅ `services/mcp-server/app/routes/auth.py` - 更新 -5. ✅ `services/mcp-server/scripts/init_test_accounts.py` - 新建 - -#### 测试代码(6个文件) -1. ✅ `services/mcp-server/tests/__init__.py` - 新建 -2. ✅ `services/mcp-server/tests/conftest.py` - 新建 -3. ✅ `services/mcp-server/tests/test_permissions.py` - 新建 -4. ✅ `services/mcp-server/tests/test_api_endpoints.py` - 新建 -5. ✅ `services/mcp-server/pytest.ini` - 新建 -6. ✅ `services/mcp-server/requirements-test.txt` - 新建 - -#### 脚本(1个文件) -1. ✅ `services/mcp-server/scripts/run_tests.sh` - 新建 - -### 7.2 文档交付(6个文件) - -1. ✅ `PERMISSIONS_UPDATE_SUMMARY.md` - 权限更新说明 -2. ✅ `PERMISSIONS_IMPLEMENTATION_COMPLETE.md` - 实施完成报告(本文档) -3. ✅ `TESTING_GUIDE.md` - 测试指南 -4. ✅ `Docs/前端开发/前端角色权限控制指南.md` - 前端指南 -5. ✅ `BACKEND_REQUIREMENTS.md` - 更新权限设计 -6. ✅ `Docs/前后端调试说明/API接口文档.md` - 更新角色说明 - -### 7.3 统计数据 - -| 类型 | 数量 | -|------|------| -| 新建文件 | 11 | -| 更新文件 | 5 | -| 代码行数 | ~3,500 | -| 测试用例 | 36 | -| 测试账号 | 10 | -| 文档页数 | ~50 | - ---- - -## 八、验证清单 - -### 8.1 功能验证 - -- ✅ 7种角色都能正常登录 -- ✅ 每个角色的权限映射正确 -- ✅ 权限检查函数工作正常 -- ✅ API端点权限控制有效 -- ✅ JWT Token认证正常 -- ✅ API Key认证正常 -- ✅ Token刷新机制正常 -- ✅ 密码修改功能正常 -- ✅ 跨角色访问被正确拒绝 -- ✅ 权限继承关系正确 - -### 8.2 测试验证 - -- ✅ 所有单元测试通过 -- ✅ 所有集成测试通过 -- ✅ 测试覆盖率 > 80% -- ✅ 测试脚本运行正常 -- ✅ 测试账号创建成功 - -### 8.3 文档验证 - -- ✅ API文档更新完整 -- ✅ 前端指南详细清晰 -- ✅ 测试指南易于理解 -- ✅ 权限更新说明完整 -- ✅ 所有示例代码可运行 - ---- - -## 九、使用指南 - -### 9.1 快速开始 - -#### 1. 创建测试账号 -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server -python scripts/init_test_accounts.py -``` - -#### 2. 运行测试 -```bash -./scripts/run_tests.sh all -``` - -#### 3. 查看覆盖率 -```bash -./scripts/run_tests.sh coverage -open htmlcov/index.html -``` - -### 9.2 开发流程 - -#### 后端开发 -1. 使用 `app/permissions.py` 中的权限定义 -2. 在路由中使用 `@require_permission` 装饰器 -3. 编写对应的测试用例 -4. 运行测试确保通过 - -#### 前端开发 -1. 参考 `Docs/前端开发/前端角色权限控制指南.md` -2. 实现登录页面的角色选择 -3. 使用 `PermissionWrapper` 控制UI显示 -4. 使用 `RoleRoute` 保护路由 -5. 测试各角色的访问权限 - ---- - -## 十、后续建议 - -### 10.1 短期(1-2周) - -1. **部署测试环境** - - 在测试环境部署更新后的代码 - - 运行完整的测试套件 - - 验证所有功能正常 - -2. **前端实现** - - 根据前端指南实现角色选择 - - 实现权限控制组件 - - 集成后端API - -3. **集成测试** - - 前后端联调测试 - - 验证所有角色的完整流程 - - 修复发现的问题 - -### 10.2 中期(1个月) - -1. **性能优化** - - 优化权限检查性能 - - 添加权限缓存机制 - - 优化数据库查询 - -2. **安全加固** - - 实现Token黑名单 - - 添加登录失败限制 - - 实现审计日志 - -3. **监控告警** - - 添加权限异常监控 - - 实现登录异常告警 - - 统计权限使用情况 - -### 10.3 长期(3个月) - -1. **功能扩展** - - 实现细粒度权限控制 - - 支持动态权限配置 - - 实现权限模板 - -2. **用户体验** - - 优化登录流程 - - 实现SSO单点登录 - - 支持多因素认证 - -3. **文档完善** - - 添加更多示例 - - 录制视频教程 - - 编写故障排查指南 - ---- - -## 十一、联系方式 - -如有任何问题或建议,请联系: - -- **项目**: Taiji AI-PAD -- **模块**: 权限系统 -- **文档**: 本报告及相关文档 -- **支持**: 参考 `TESTING_GUIDE.md` 中的常见问题 - ---- - -## 十二、变更历史 - -| 版本 | 日期 | 变更内容 | 作者 | -|------|------|---------|------| -| 1.0 | 2025-12-25 | 初始版本,完成权限系统实施 | AI Assistant | - ---- - -**报告状态**: ✅ 已完成 -**最后更新**: 2025-12-25 -**下一步行动**: 部署测试环境并进行集成测试 - diff --git a/PERMISSIONS_UPDATE_SUMMARY.md b/PERMISSIONS_UPDATE_SUMMARY.md deleted file mode 100644 index ab72210..0000000 --- a/PERMISSIONS_UPDATE_SUMMARY.md +++ /dev/null @@ -1,183 +0,0 @@ -# 权限设计更新说明 - -## 更新日期 -2025-12-25 - -## 更新概述 -根据新的需求,权限系统已从原来的3种管理员角色扩展到4种管理员角色,使角色分工更加明确。 - -## 角色体系变更 - -### 更新前 -系统支持3种管理员角色: -- 计费管理员 -- 运营管理员 -- 超级管理员 - -### 更新后 -系统现在支持7种角色,其中包含4种管理员角色: - -| 角色代码 | 角色名称 | 说明 | 权限范围 | -|---------|---------|------|---------| -| `user` | 租户用户 | 普通用户,使用平台服务 | 查看自己的资源和账单 | -| `channel_admin` | 渠道管理员 | 管理渠道下的租户和资源 | 租户管理、资源分配、计费管理 | -| `billing_admin` | **计费管理员** | 负责计费、充值等财务操作 | 查看和管理计费记录、充值操作 | -| `operations_admin` | **运营管理员** | 负责租户和资源的日常运营管理 | 租户管理、资源管理、查看计费 | -| `admin` | **管理员** | 平台管理员,拥有除超级管理员外的大部分权限 | 租户、资源、计费、设置、监控等综合管理权限 | -| `super_admin` | **超级管理员** | 拥有全部权限,可进行所有管理操作 | 全部权限 | -| `provider_admin` | 供应商管理员 | 管理供应商的模型和配置 | 模型管理 | - -## 权限列表扩展 - -新增了以下权限: -- `manage:channels` - 管理渠道 -- `manage:providers` - 管理供应商 -- `view:monitoring` - 查看监控 - -完整权限列表: -| 权限 | 说明 | -|------|------| -| view:overview | 查看概览 | -| manage:tenants | 管理租户 | -| manage:resources | 管理资源 | -| view:billing | 查看计费 | -| manage:billing | 管理计费(含充值) | -| manage:settings | 管理设置 | -| approve:applications | 审批申请 | -| manage:channels | 管理渠道 | -| manage:providers | 管理供应商 | -| view:monitoring | 查看监控 | - -## 角色权限映射 - -| 角色 | 权限列表 | -|------|---------| -| **计费管理员** (billing_admin) | view:overview, view:billing, manage:billing | -| **运营管理员** (operations_admin) | view:overview, manage:tenants, manage:resources, view:billing | -| **管理员** (admin) | view:overview, manage:tenants, manage:resources, view:billing, manage:billing, manage:settings, view:monitoring | -| **超级管理员** (super_admin) | 全部权限 | - -## 代码更新内容 - -### 1. 数据模型 (`services/mcp-server/models.py`) -- 更新 `User.role` 字段注释,添加新的角色类型 - -### 2. 权限管理模块 (`services/mcp-server/app/permissions.py`) -- **新建文件**:专门的权限管理模块 -- 定义完整的权限列表和角色权限映射 -- 提供权限检查辅助函数: - - `get_role_permissions()` - 获取角色权限列表 - - `has_permission()` - 检查是否拥有某个权限 - - `has_any_permission()` - 检查是否拥有任意权限 - - `has_all_permissions()` - 检查是否拥有所有权限 - - `require_permission()` - 权限装饰器 - -### 3. API Schema (`services/mcp-server/app/schemas.py`) -- 更新 `LoginRequest` 的 `role` 字段验证,支持新的角色类型 - -### 4. 认证路由 (`services/mcp-server/app/routes/auth.py`) -- 更新登录接口文档,说明所有支持的角色 -- 优化角色验证逻辑,支持层级角色验证: - - 超级管理员可以使用任何管理员登录入口 - - 管理员可以使用计费/运营管理员登录入口 - -### 5. 文档更新 -- `BACKEND_REQUIREMENTS.md` - 更新权限设计章节 -- `Docs/前后端调试说明/API接口文档.md` - 更新角色说明表 -- `Docs/项目文档/项目工作流程.md` - 更新认证与权限说明 - -## 使用示例 - -### 计费管理员登录 -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "billing@example.com", - "password": "billing123", - "role": "billing_admin" - }' -``` - -### 运营管理员登录 -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "ops@example.com", - "password": "ops123", - "role": "operations_admin" - }' -``` - -### 管理员登录 -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "admin@example.com", - "password": "admin123", - "role": "admin" - }' -``` - -### 超级管理员登录 -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "superadmin@example.com", - "password": "superadmin123", - "role": "super_admin" - }' -``` - -## 权限检查示例 - -在代码中使用权限检查: - -```python -from app.permissions import has_permission, require_permission - -# 检查用户是否有计费管理权限 -if has_permission(user.role, "manage:billing"): - # 执行计费操作 - pass - -# 使用装饰器要求权限 -@require_permission("manage:tenants") -async def create_tenant(principal: dict): - # 创建租户 - pass -``` - -## 注意事项 - -1. **向后兼容**:原有的用户、渠道管理员、超级管理员和供应商管理员角色保持不变 -2. **角色层级**:角色之间有明确的权限层级关系,高权限角色可以执行低权限角色的所有操作 -3. **数据库迁移**:需要在数据库中为现有管理员账号分配具体的角色类型(billing_admin、operations_admin、admin 或 super_admin) -4. **前端适配**:前端需要更新登录界面和角色选择逻辑,支持新的4种管理员角色 -5. **权限验证**:所有需要权限控制的API端点都应使用 `permissions.py` 模块进行权限验证 - -## 测试建议 - -1. 为每种管理员角色创建测试账号 -2. 验证每个角色只能访问其权限范围内的API -3. 测试角色层级关系,确保高权限角色可以执行低权限操作 -4. 测试登录接口对不同角色的验证逻辑 -5. 验证权限装饰器在API路由中的正确使用 - -## 下一步行动 - -1. ✅ 更新后端代码和文档 -2. ⬜ 在数据库中创建测试账号 -3. ⬜ 前端更新角色选择和权限控制 -4. ⬜ 编写权限测试用例 -5. ⬜ 部署到测试环境验证 - ---- - -**文档版本**: 1.0 -**最后更新**: 2025-12-25 -**更新人**: AI Assistant - diff --git a/QUICK_START.md b/QUICK_START.md deleted file mode 100644 index 8c10a66..0000000 --- a/QUICK_START.md +++ /dev/null @@ -1,372 +0,0 @@ -# Taiji AI PAD 后端快速开始指南 - -## 概述 - -本指南将帮助你在5分钟内启动Taiji AI PAD后端服务。 - -## 快速启动(本地开发) - -### 1. 克隆并进入项目 - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server -``` - -### 2. 安装依赖 - -```bash -# 创建虚拟环境(推荐) -python -m venv venv -source venv/bin/activate # Linux/Mac -# 或 -venv\Scripts\activate # Windows - -# 安装依赖 -pip install -r requirements.txt -``` - -### 3. 配置环境变量(可选) - -创建 `.env` 文件: - -```bash -cat > .env << EOF -# 应用环境 -ENVIRONMENT=development -DEBUG=true - -# 数据库(使用Azure PostgreSQL) -DATABASE_URL=postgresql+asyncpg://taiji:By%40123456.@taijipda.postgres.database.azure.com:5432/postgres?sslmode=require - -# Redis(使用Azure Redis) -REDIS_URL=rediss://:nkJgt1ERFpdeYrEFNyFtsc5K4ycvx2jIeAzCaGGf1OQ%3D@taiji.southeastasia.redis.azure.net:10000/0?ssl_cert_reqs=none - -# JWT密钥 -JWT_SECRET=zsbgnw - -# 加密密钥 -ENCRYPTION_KEY=zsbgnw -EOF -``` - -### 4. 初始化数据库 - -```bash -python -c "from database import init_db; import asyncio; asyncio.run(init_db())" -``` - -### 5. 启动服务 - -```bash -python main.py -``` - -服务将在 `http://localhost:8000` 启动。 - -### 6. 验证服务 - -打开浏览器访问: -- API文档: http://localhost:8000/docs -- 健康检查: http://localhost:8000/health - -## 测试API - -### 登录获取Token - -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "admin@taiji-ai.com", - "password": "admin123", - "role": "user" - }' -``` - -将返回的token保存: - -```bash -export TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." -``` - -### 测试用户API - -```bash -# 获取仪表板统计 -curl http://localhost:8000/api/user/dashboard/stats \ - -H "Authorization: Bearer $TOKEN" - -# 获取余额 -curl http://localhost:8000/api/user/billing/balance \ - -H "Authorization: Bearer $TOKEN" -``` - -## Docker部署(本地测试) - -### 1. 构建镜像 - -```bash -docker build -t mcp-server:latest . -``` - -### 2. 运行容器 - -```bash -docker run -d \ - --name mcp-server \ - -p 8000:8000 \ - -e DATABASE_URL="postgresql+asyncpg://taiji:By%40123456.@taijipda.postgres.database.azure.com:5432/postgres?sslmode=require" \ - -e REDIS_URL="rediss://:nkJgt1ERFpdeYrEFNyFtsc5K4ycvx2jIeAzCaGGf1OQ%3D@taiji.southeastasia.redis.azure.net:10000/0?ssl_cert_reqs=none" \ - mcp-server:latest -``` - -### 3. 查看日志 - -```bash -docker logs -f mcp-server -``` - -## Azure AKS部署(生产环境) - -### 前置条件 - -- Azure CLI已安装 -- kubectl已安装 -- 已创建AKS集群 -- 已配置ACR - -### 一键部署 - -```bash -# 设置环境变量 -export RESOURCE_GROUP="taiji-ai-rg" -export AKS_CLUSTER_NAME="taiji-aks-cluster" -export ACR_NAME="taijiregistry" -export LOCATION="southeastasia" - -# 运行部署脚本 -cd scripts -chmod +x deploy-azure.sh -./deploy-azure.sh -``` - -详细部署步骤请参考 `DEPLOY_AZURE.md`。 - -## 目录结构 - -``` -services/mcp-server/ -├── app/ # 应用代码 -│ ├── routes/ # API路由 -│ │ ├── auth.py # 认证 -│ │ ├── user.py # 用户侧 -│ │ ├── channel.py # 渠道 -│ │ ├── admin.py # 管理员 -│ │ └── providers.py # 供应商 -│ ├── billing.py # 计费逻辑 -│ ├── schemas.py # Pydantic模型 -│ └── auth.py # 认证工具 -├── models.py # 数据库模型 -├── database.py # 数据库配置 -├── config.py # 配置管理 -├── main.py # 应用入口 -├── requirements.txt # Python依赖 -├── Dockerfile # Docker配置 -├── k8s/ # Kubernetes配置 -│ ├── deployment.yaml -│ ├── secrets.yaml -│ └── ingress.yaml -└── scripts/ # 部署脚本 - └── deploy-azure.sh -``` - -## API端点概览 - -### 认证 (/api/auth) -- `POST /login` - 登录 -- `POST /logout` - 登出 -- `POST /refresh` - 刷新Token -- `PUT /password` - 修改密码 -- `GET /keys/info` - 获取API密钥 -- `POST /keys/regenerate` - 重新生成密钥 - -### 用户 (/api/user) -- `GET /dashboard/stats` - 仪表板统计 -- `GET /agents/activity` - Agent活动 -- `POST /gateway/select` - 选择网关 -- `POST /tools/generate` - 生成工具 -- `GET /agents/platform` - 平台Agent -- `POST /workflows/create` - 创建工作流 -- `GET /billing/balance` - 获取余额 -- `POST /billing/recharge` - 充值 - -### 渠道 (/api/channel) -- `GET /tenants` - 租户列表 -- `POST /tenants/create` - 创建租户 -- `POST /tenants/{id}/recharge` - 充值 -- `PUT /tenants/{id}/credit` - 设置授信 -- `GET /billing/stats` - 计费统计 - -### 管理员 (/api/admin) -- `GET /dashboard/stats` - 平台统计 -- `GET /channels` - 渠道列表 -- `POST /channels/create` - 创建渠道 -- `GET /channels/applications` - 申请列表 -- `PUT /channels/applications/{id}/review` - 审批 -- `GET /billing/overview` - 三维度计费 - -### 供应商 (/api/providers) -- `GET /models` - 模型供应商列表 -- `POST /models/create` - 创建供应商 -- `GET /models/{id}` - 供应商详情 -- `PUT /models/{id}` - 更新供应商 - -## 核心功能 - -### EU计算 -```python -# 1 EU = 10秒,不足10秒按1 EU -duration = 60 # 秒 -eu = math.ceil(duration / 10) # 6 EU -cost = eu * 0.01 # ¥0.06 -``` - -### 余额与授信 -```python -可用额度 = 账户余额 + 授信额度 -# 消费优先扣除余额,余额不足使用授信 -``` - -### 工作流限制 -```python -# 最多3个Agent节点 -if len(nodes) > 3: - raise ValueError("工作流最多支持3个Agent节点") -``` - -## 常见问题 - -### Q: 数据库连接失败? - -确保防火墙规则允许你的IP访问Azure Database for PostgreSQL: - -```bash -az postgres flexible-server firewall-rule create \ - --resource-group taiji-ai-rg \ - --name taijipda \ - --rule-name MyIP \ - --start-ip-address YOUR_IP \ - --end-ip-address YOUR_IP -``` - -### Q: Redis连接超时? - -检查Azure Cache for Redis的访问策略和防火墙设置。 - -### Q: 如何创建初始管理员账号? - -数据库初始化时会自动创建: -- 用户名: admin -- 邮箱: admin@taiji-ai.com -- 密码: admin123 -- 角色: super_admin - -**生产环境务必修改密码!** - -### Q: 如何查看日志? - -本地开发: -```bash -tail -f logs/mcp-server.log -``` - -Docker: -```bash -docker logs -f mcp-server -``` - -Kubernetes: -```bash -kubectl logs -f -l app=mcp-server -n taiji-ai -``` - -### Q: 如何更新部署? - -```bash -# 构建新镜像 -docker build -t ${ACR_NAME}.azurecr.io/mcp-server:v2 . -docker push ${ACR_NAME}.azurecr.io/mcp-server:v2 - -# 更新K8s部署 -kubectl set image deployment/mcp-server \ - mcp-server=${ACR_NAME}.azurecr.io/mcp-server:v2 \ - -n taiji-ai - -# 查看滚动更新状态 -kubectl rollout status deployment/mcp-server -n taiji-ai -``` - -## 监控和调试 - -### 健康检查 - -```bash -curl http://localhost:8000/health -``` - -### Prometheus指标 - -```bash -curl http://localhost:8000/metrics -``` - -### 数据库状态 - -```python -from database import health_check -import asyncio - -result = asyncio.run(health_check()) -print(result) -``` - -## 性能优化建议 - -1. **数据库连接池**: 已配置20个连接 -2. **Redis缓存**: 用于会话和临时数据 -3. **异步I/O**: 使用AsyncIO提高并发 -4. **索引优化**: 主要查询字段已添加索引 -5. **HPA扩缩容**: 生产环境自动扩缩容 - -## 安全建议 - -1. **生产环境必须**: - - 修改默认密码 - - 使用强JWT密钥 - - 启用HTTPS - - 配置防火墙规则 - - 定期备份数据库 - -2. **推荐使用**: - - Azure Key Vault存储密钥 - - Azure Monitor监控 - - 定期安全扫描 - - API速率限制 - -## 下一步 - -- 📖 阅读完整部署指南: `DEPLOY_AZURE.md` -- ✅ 运行验证测试: `BACKEND_VERIFICATION.md` -- 📝 查看实现总结: `BACKEND_IMPLEMENTATION_SUMMARY.md` -- 🔍 查看API文档: http://localhost:8000/docs - -## 获取帮助 - -- 📧 Email: admin@taiji-ai.com -- 📚 文档: 查看项目根目录的所有MD文件 -- 🐛 问题追踪: GitHub Issues - ---- - -**祝你使用愉快!** 🎉 - diff --git a/TESTING_GUIDE.md b/TESTING_GUIDE.md deleted file mode 100644 index edd3bc8..0000000 --- a/TESTING_GUIDE.md +++ /dev/null @@ -1,493 +0,0 @@ -# 权限系统测试指南 - -## 文档版本 -- **版本**: 1.0 -- **更新日期**: 2025-12-25 -- **适用范围**: Taiji AI-PAD 后端测试 - ---- - -## 目录 -1. [测试概述](#测试概述) -2. [环境准备](#环境准备) -3. [运行测试](#运行测试) -4. [测试用例说明](#测试用例说明) -5. [测试账号](#测试账号) -6. [手动测试](#手动测试) -7. [CI/CD集成](#cicd集成) - ---- - -## 测试概述 - -本项目包含完整的权限系统测试,覆盖以下方面: - -### 测试类型 -- ✅ **单元测试**: 测试权限检查函数、角色权限映射 -- ✅ **集成测试**: 测试API端点的权限控制 -- ✅ **认证测试**: 测试登录、登出、Token刷新 -- ✅ **授权测试**: 测试基于角色的访问控制(RBAC) - -### 测试覆盖 -- 7种用户角色的权限测试 -- 10种权限的验证测试 -- 50+ API端点的访问控制测试 -- JWT Token和API Key认证测试 -- 跨角色访问控制测试 - ---- - -## 环境准备 - -### 1. 安装依赖 - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server - -# 安装项目依赖 -pip install -r requirements.txt - -# 安装测试依赖 -pip install -r requirements-test.txt -``` - -### 2. 测试依赖说明 - -``` -pytest==7.4.3 # 测试框架 -pytest-asyncio==0.21.1 # 异步测试支持 -pytest-cov==4.1.0 # 代码覆盖率 -httpx==0.25.2 # HTTP客户端(用于API测试) -aiosqlite==0.19.0 # SQLite异步驱动(用于测试数据库) -pytest-mock==3.12.0 # Mock支持 -faker==20.1.0 # 测试数据生成 -``` - ---- - -## 运行测试 - -### 方法1: 使用测试脚本(推荐) - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server - -# 运行所有测试 -./scripts/run_tests.sh all - -# 只运行权限测试 -./scripts/run_tests.sh permissions - -# 只运行API测试 -./scripts/run_tests.sh api - -# 运行测试并生成覆盖率报告 -./scripts/run_tests.sh coverage - -# 快速测试(跳过慢速测试) -./scripts/run_tests.sh quick -``` - -### 方法2: 直接使用pytest - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server - -# 运行所有测试 -pytest tests/ -v - -# 运行特定测试文件 -pytest tests/test_permissions.py -v - -# 运行特定测试类 -pytest tests/test_permissions.py::TestPermissions -v - -# 运行特定测试用例 -pytest tests/test_permissions.py::TestPermissions::test_role_permissions_mapping -v - -# 生成覆盖率报告 -pytest tests/ --cov=app --cov=models --cov-report=html - -# 查看覆盖率报告 -open htmlcov/index.html # macOS -xdg-open htmlcov/index.html # Linux -``` - -### 方法3: 使用pytest标记 - -```bash -# 只运行权限相关测试 -pytest -m permissions - -# 只运行API测试 -pytest -m api - -# 只运行单元测试 -pytest -m unit - -# 只运行集成测试 -pytest -m integration - -# 跳过慢速测试 -pytest -m "not slow" -``` - ---- - -## 测试用例说明 - -### 1. 权限系统测试 (`test_permissions.py`) - -#### TestPermissions - 权限映射测试 -```python -test_role_permissions_mapping() # 测试角色权限映射 -test_has_permission() # 测试权限检查函数 -``` - -**测试内容**: -- 验证每个角色的权限列表 -- 验证权限检查函数的正确性 -- 验证超级管理员拥有所有权限 - -#### TestAuthenticationAPI - 认证API测试 -```python -test_login_success() # 测试成功登录 -test_login_wrong_password() # 测试错误密码 -test_login_wrong_role() # 测试错误角色 -test_login_all_roles() # 测试所有角色登录 -``` - -**测试内容**: -- 验证登录流程 -- 验证密码验证 -- 验证角色验证 -- 验证Token生成 - -#### TestRoleBasedAccess - 基于角色的访问控制 -```python -test_super_admin_access() # 测试超级管理员访问 -test_billing_admin_access() # 测试计费管理员访问 -test_operations_admin_access() # 测试运营管理员访问 -test_user_limited_access() # 测试普通用户受限访问 -``` - -**测试内容**: -- 验证每个角色能访问的API端点 -- 验证每个角色不能访问的API端点 -- 验证403权限不足响应 - -#### TestAPIKeyAuthentication - API密钥认证 -```python -test_api_key_authentication() # 测试API密钥认证 -test_invalid_api_key() # 测试无效API密钥 -``` - -**测试内容**: -- 验证API密钥认证流程 -- 验证无效密钥的拒绝 - -#### TestTokenRefresh - Token刷新 -```python -test_refresh_token() # 测试刷新Token -``` - -**测试内容**: -- 验证Token刷新机制 -- 验证新旧Token的区别 - -#### TestPasswordChange - 密码修改 -```python -test_change_password() # 测试修改密码 -test_change_password_wrong_old_password() # 测试错误旧密码 -``` - -**测试内容**: -- 验证密码修改流程 -- 验证旧密码验证 - -#### TestCrossRoleAccess - 跨角色访问 -```python -test_channel_admin_cannot_access_other_channels() # 测试渠道隔离 -``` - -**测试内容**: -- 验证渠道管理员只能访问自己渠道的数据 -- 验证数据隔离 - -#### TestPermissionInheritance - 权限继承 -```python -test_admin_has_billing_permissions() # 测试管理员继承计费权限 -test_admin_has_operations_permissions() # 测试管理员继承运营权限 -test_super_admin_has_all_permissions() # 测试超级管理员拥有全部权限 -``` - -**测试内容**: -- 验证角色权限的层级关系 -- 验证高级角色包含低级角色的权限 - -### 2. API端点测试 (`test_api_endpoints.py`) - -#### TestUserAPIs - 用户端API -```python -test_get_dashboard_stats() # 测试获取仪表板统计 -test_get_billing_records() # 测试获取计费记录 -test_user_cannot_access_admin_apis() # 测试用户无法访问管理员API -``` - -#### TestChannelAPIs - 渠道端API -```python -test_get_channel_dashboard_stats() # 测试获取渠道仪表板 -test_get_channel_tenants() # 测试获取渠道租户列表 -``` - -#### TestAdminAPIs - 管理员API -```python -test_super_admin_get_channels() # 测试超级管理员获取渠道 -test_admin_get_dashboard_stats() # 测试管理员获取仪表板 -``` - -#### TestBillingAdminAPIs - 计费管理员API -```python -test_billing_admin_view_billing() # 测试查看计费 -test_billing_admin_manage_billing() # 测试管理计费 -test_billing_admin_cannot_manage_tenants() # 测试无法管理租户 -``` - -#### TestOperationsAdminAPIs - 运营管理员API -```python -test_operations_admin_manage_tenants() # 测试管理租户 -test_operations_admin_manage_resources() # 测试管理资源 -test_operations_admin_cannot_recharge() # 测试无法充值 -``` - -#### TestProviderAPIs - 供应商API -```python -test_provider_admin_get_models() # 测试获取模型列表 -test_provider_admin_cannot_access_admin_apis() # 测试无法访问管理员API -``` - ---- - -## 测试账号 - -### 自动创建测试账号 - -运行以下脚本创建所有测试账号: - -```bash -cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server -python scripts/init_test_accounts.py -``` - -### 测试账号列表 - -| 角色 | 邮箱 | 密码 | 登录角色 | -|------|------|------|---------| -| 超级管理员 | superadmin@test.com | super123 | super_admin | -| 管理员 | admin@test.com | admin123 | admin | -| 管理员xiaohei | xiaohei@test.com | 1233456 | admin | -| 计费管理员 | billing@test.com | billing123 | billing_admin | -| 运营管理员 | operations@test.com | ops123 | operations_admin | -| 渠道管理员A | channel-admin-a@test.com | channel123 | channel | -| 渠道管理员B | channel-admin-b@test.com | channel123 | channel | -| 供应商管理员 | provider@test.com | provider123 | provider | -| 测试用户1 | user1@test.com | user123 | user | -| 测试用户2 | user2@test.com | user123 | user | -| 测试用户3 | user3@test.com | user123 | user | - ---- - -## 手动测试 - -### 1. 测试登录 - -```bash -# 超级管理员登录 -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "superadmin@test.com", - "password": "super123", - "role": "super_admin" - }' - -# 计费管理员登录 -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "billing@test.com", - "password": "billing123", - "role": "billing_admin" - }' - -# 运营管理员登录 -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{ - "email": "operations@test.com", - "password": "ops123", - "role": "operations_admin" - }' -``` - -### 2. 测试权限控制 - -```bash -# 保存token -TOKEN="<从登录响应中获取的token>" - -# 测试访问用户仪表板(所有角色都应该能访问) -curl -X GET http://localhost:8000/api/user/dashboard/stats \ - -H "Authorization: Bearer $TOKEN" - -# 测试访问管理员端点(只有管理员角色能访问) -curl -X GET http://localhost:8000/api/admin/dashboard/stats \ - -H "Authorization: Bearer $TOKEN" - -# 测试计费管理(只有计费管理员、管理员、超级管理员能访问) -curl -X GET http://localhost:8000/api/admin/billing/records \ - -H "Authorization: Bearer $TOKEN" - -# 测试租户管理(只有运营管理员、管理员、超级管理员能访问) -curl -X GET http://localhost:8000/api/admin/tenants \ - -H "Authorization: Bearer $TOKEN" -``` - -### 3. 测试权限拒绝 - -```bash -# 用普通用户token访问管理员端点(应该返回403) -USER_TOKEN="<普通用户的token>" - -curl -X GET http://localhost:8000/api/admin/dashboard/stats \ - -H "Authorization: Bearer $USER_TOKEN" - -# 预期响应: 403 Forbidden -``` - ---- - -## CI/CD集成 - -### GitHub Actions示例 - -```yaml -name: Run Tests - -on: - push: - branches: [ main, develop ] - pull_request: - branches: [ main, develop ] - -jobs: - test: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: '3.11' - - - name: Install dependencies - run: | - cd services/mcp-server - pip install -r requirements.txt - pip install -r requirements-test.txt - - - name: Run tests - run: | - cd services/mcp-server - pytest tests/ -v --cov=app --cov=models --cov-report=xml - - - name: Upload coverage - uses: codecov/codecov-action@v3 - with: - file: ./services/mcp-server/coverage.xml -``` - -### GitLab CI示例 - -```yaml -test: - stage: test - image: python:3.11 - script: - - cd services/mcp-server - - pip install -r requirements.txt - - pip install -r requirements-test.txt - - pytest tests/ -v --cov=app --cov=models --cov-report=term - coverage: '/TOTAL.*\s+(\d+%)$/' -``` - ---- - -## 测试最佳实践 - -### 1. 测试前准备 -- ✅ 确保数据库连接正常 -- ✅ 清理测试数据库 -- ✅ 创建必要的测试账号 - -### 2. 测试中注意 -- ✅ 每个测试应该独立运行 -- ✅ 使用fixtures管理测试数据 -- ✅ 测试后清理数据 - -### 3. 测试覆盖率目标 -- ✅ 总体覆盖率 > 80% -- ✅ 核心权限模块覆盖率 > 95% -- ✅ API路由覆盖率 > 90% - -### 4. 持续改进 -- ✅ 定期运行测试 -- ✅ 新功能必须有测试 -- ✅ Bug修复必须有回归测试 - ---- - -## 常见问题 - -### Q1: 测试失败怎么办? -A: 查看详细错误信息,检查: -- 数据库连接是否正常 -- 测试依赖是否完整安装 -- 测试数据是否正确创建 - -### Q2: 如何调试单个测试? -A: 使用pytest的调试选项: -```bash -pytest tests/test_permissions.py::TestPermissions::test_role_permissions_mapping -vv -s -``` - -### Q3: 如何查看测试覆盖率? -A: 运行覆盖率测试并查看报告: -```bash -./scripts/run_tests.sh coverage -open htmlcov/index.html -``` - -### Q4: 测试运行很慢怎么办? -A: 使用快速测试模式: -```bash -./scripts/run_tests.sh quick -``` - ---- - -## 参考资料 - -- [Pytest文档](https://docs.pytest.org/) -- [FastAPI测试文档](https://fastapi.tiangolo.com/tutorial/testing/) -- [权限更新说明](./PERMISSIONS_UPDATE_SUMMARY.md) -- [API接口文档](./Docs/前后端调试说明/API接口文档.md) - ---- - -**文档版本**: 1.0 -**最后更新**: 2025-12-25 -**维护人**: Taiji AI-PAD Team - diff --git a/docker-compose.yml b/docker-compose.yml index 263385c..ca9b105 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,35 +17,6 @@ services: - taiji-network restart: unless-stopped - # Redis 缓存 - redis: - image: redis:7-alpine - container_name: taiji-redis - ports: - - "6379:6379" - command: ["redis-server", "--appendonly", "yes"] - volumes: - - redis_data:/data - networks: - - taiji-network - restart: unless-stopped - - # PostgreSQL 数据库 - postgres: - image: postgres:15-alpine - container_name: taiji-postgres - ports: - - "5432:5432" - environment: - - POSTGRES_DB=${POSTGRES_DB} - - POSTGRES_USER=${POSTGRES_USER} - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - volumes: - - postgres_data:/var/lib/postgresql/data - networks: - - taiji-network - restart: unless-stopped - # LiteLLM网关服务 litellm-gateway: build: @@ -92,8 +63,6 @@ services: - ./logs:/app/logs depends_on: - nats - - redis - - postgres networks: - taiji-network restart: unless-stopped @@ -118,8 +87,6 @@ services: depends_on: - nats - litellm-gateway - - redis - - postgres networks: - taiji-network restart: unless-stopped @@ -252,6 +219,4 @@ volumes: nats_data: prometheus_data: grafana_data: - redis_data: - postgres_data: diff --git a/scripts/api_flow_tester.py b/scripts/api_flow_tester.py deleted file mode 100644 index b02a30d..0000000 --- a/scripts/api_flow_tester.py +++ /dev/null @@ -1,312 +0,0 @@ -#!/usr/bin/env python3 -"""End-to-end flow tester for taiji-AI-PAD services.""" -from __future__ import annotations - -import argparse -import sys -import uuid -from dataclasses import dataclass -from typing import Any, Dict, Iterable, Optional - -import requests - - -@dataclass -class ServiceConfig: - data_ingestion_url: str = "http://localhost:8001" - mcp_server_url: str = "http://localhost:8002" - timeout: int = 30 - - -class ApiFlowTester: - def __init__(self, config: ServiceConfig, verbose: bool = True) -> None: - self.config = config - self.session = requests.Session() - self.verbose = verbose - - def run(self, skip_data_ingestion: bool, skip_mcp: bool) -> None: - if not skip_data_ingestion: - self._log("Running Data Ingestion flow") - self._test_data_ingestion_flow() - else: - self._log("Skipping Data Ingestion flow") - - if not skip_mcp: - self._log("Running MCP Server flow") - self._test_mcp_flow() - else: - self._log("Skipping MCP Server flow") - - def _test_data_ingestion_flow(self) -> None: - base = self.config.data_ingestion_url - - self._log("Checking Data Ingestion health endpoint") - health = self._json_request("GET", f"{base}/health") - self._ensure_service_health( - health, - critical_keys=["data_ingestion"], - context="Data Ingestion", - ) - - self._log("Triggering RapidAPI sync job") - sync_response = self._json_request( - "POST", - f"{base}/rapidapi/sync", - params={"category": "weather", "limit": 1}, - ) - self._require("message" in sync_response, "RapidAPI sync did not return confirmation", sync_response) - - self._log("Parsing reference OpenAPI specification") - openapi_url = "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.yaml" - openapi = self._json_request("POST", f"{base}/openapi/parse", params={"url": openapi_url}) - self._require(openapi.get("parsed_data"), "OpenAPI parse missing parsed_data", openapi) - - self._log("Running APILLAMA processing step") - apillama_payload = { - "api_doc": { - "title": "Weather API", - "description": "Returns forecast information", - "parameters": [ - {"name": "location", "type": "string", "description": "City name", "required": True} - ], - }, - "context": {"service": "weather", "version": "1.0"}, - "output_format": "json_schema", - "include_examples": True, - "enhance_descriptions": True, - "validate_schema": True, - } - apillama = self._json_request("POST", f"{base}/apillama/process", json=apillama_payload) - self._require(apillama.get("processed"), "APILLAMA processing failed", apillama) - - self._log("Requesting tool generation task") - tool_payload = { - "url": "https://api.example.com/weather", - "method": "GET", - "name": f"diag_get_weather_{uuid.uuid4().hex[:8]}", - "description": "Diagnostic weather fetch tool", - "parameters": [ - { - "name": "location", - "type": "string", - "location": "query", - "description": "City name", - "required": True, - }, - { - "name": "unit", - "type": "string", - "location": "query", - "description": "Measurement unit", - "required": False, - }, - ], - "request_body": None, - "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "temperature": {"type": "number"}, - "condition": {"type": "string"}, - }, - } - } - }, - } - }, - "security": [], - "tags": ["weather"], - "deprecated": False, - "headers": {"Authorization": "Bearer demo-token"}, - } - tool_gen = self._json_request("POST", f"{base}/tools/generate", json=tool_payload) - self._require( - tool_gen.get("message"), - "Tool generation endpoint did not acknowledge request", - tool_gen, - ) - - self._log("Listing generated tools") - tools = self._json_request("GET", f"{base}/tools", params={"limit": 5}) - self._require(isinstance(tools, list), "Tools endpoint did not return a list", tools) - if tools: - self._log("Fetching first tool definition for verification") - first_tool = tools[0]["name"] - definition = self._json_request("GET", f"{base}/tools/{first_tool}") - self._require( - definition.get("name") == first_tool, - "Fetched tool definition does not match", - definition, - ) - - self._log("Reading Data Ingestion metrics endpoint") - metrics_text = self._request("GET", f"{base}/metrics").text - self._require("http_requests_total" in metrics_text, "Metrics output missing expected counters") - - def _test_mcp_flow(self) -> None: - base = self.config.mcp_server_url - - self._log("Checking MCP health endpoint") - health = self._json_request("GET", f"{base}/health") - self._ensure_service_health( - health, - critical_keys=["database"], - context="MCP", - ) - - self._log("Fetching current MCP agent list") - existing_agents = self._json_request("GET", f"{base}/agents", params={"skip": 0, "limit": 100}) - self._require(isinstance(existing_agents, list), "Agent list did not return a list", existing_agents) - existing_ids = {agent.get("id") for agent in existing_agents if agent.get("id")} - - self._log("Registering diagnostic agent") - agent_name = f"auto-agent-{uuid.uuid4().hex[:8]}" - agent_payload = { - "name": agent_name, - "description": "Auto-generated diagnostic agent", - "role": "assistant", - "goal": "Validate MCP server flows", - "tools": ["math_add"], - "config": {"default_model": "gpt-4o-mini"}, - "capabilities": ["diagnostics"], - } - created_agent = self._json_request("POST", f"{base}/agents", json=agent_payload) - agent_id = created_agent.get("id") - self._require(agent_id, "Agent creation response missing id", created_agent) - - self._log("Verifying new agent presence in list") - refreshed_agents = self._json_request("GET", f"{base}/agents", params={"skip": 0, "limit": 100}) - after_ids = {agent.get("id") for agent in refreshed_agents if agent.get("id")} - self._require(agent_id in after_ids, "New agent not found in list after creation") - - self._log("Fetching newly created agent details") - fetched_agent = self._json_request("GET", f"{base}/agents/{agent_id}") - self._require(fetched_agent.get("name") == agent_name, "Fetched agent does not match created agent", fetched_agent) - - self._log("Executing math_add tool via MCP agent") - execution_payload = { - "jsonrpc": "2.0", - "id": f"exec-{uuid.uuid4().hex[:8]}", - "method": "tools/call", - "params": { - "tool": {"name": "math_add", "function_name": "math_add"}, - "arguments": {"a": 1, "b": 2}, - "context": {"session_id": f"session-{agent_id[:8]}"}, - }, - } - execution = self._json_request("POST", f"{base}/agents/{agent_id}/execute", json=execution_payload) - self._require(execution.get("success"), "Agent tool execution failed", execution) - self._require(execution.get("result") == 3, "math_add result mismatch", execution) - - self._log("Listing MCP tools for visibility") - tools = self._json_request("GET", f"{base}/tools", params={"limit": 5}) - self._require(isinstance(tools, list), "MCP tools endpoint did not return a list", tools) - - self._log("Reading MCP metrics endpoint") - metrics_text = self._request("GET", f"{base}/metrics").text - self._require("http_requests_total" in metrics_text, "MCP metrics missing expected counters") - - self._log("Fetching monitoring metrics snapshot") - monitoring = self._json_request("GET", f"{base}/api/v1/monitoring/metrics") - self._require( - monitoring.get("system"), - "Monitoring metrics missing system section", - monitoring, - ) - - def _request( - self, - method: str, - url: str, - *, - expected_status: Optional[Iterable[int]] = None, - **kwargs: Any, - ) -> requests.Response: - response = self.session.request(method, url, timeout=self.config.timeout, **kwargs) - acceptable = list(expected_status) if expected_status is not None else [] - if expected_status is None and not 200 <= response.status_code < 300: - raise AssertionError( - f"Request to {url} failed with status {response.status_code}: {response.text[:200]}" - ) - if expected_status is not None and response.status_code not in acceptable: - raise AssertionError( - f"Request to {url} expected {acceptable} but received {response.status_code}: {response.text[:200]}" - ) - return response - - def _json_request(self, method: str, url: str, **kwargs: Any) -> Dict[str, Any] | Any: - response = self._request(method, url, **kwargs) - try: - return response.json() - except ValueError as exc: # pragma: no cover - defensive guard - raise AssertionError(f"Response from {url} is not valid JSON: {response.text[:200]}") from exc - - def _require(self, condition: bool, message: str, payload: Optional[Any] = None) -> None: - if not condition: - detail = f" | payload={payload}" if payload is not None else "" - raise AssertionError(f"{message}{detail}") - - def _ensure_service_health( - self, - payload: Dict[str, Any], - *, - critical_keys: Optional[Iterable[str]] = None, - context: str, - ) -> None: - status = str(payload.get("status", "")).lower() - acceptable = {"healthy", "ok", "degraded"} - services = payload.get("services") or {} - if status not in acceptable: - raise AssertionError(f"{context} health status unacceptable: {status} | payload={payload}") - if critical_keys: - missing = [svc for svc in critical_keys if services.get(svc) not in {"healthy", "ok"}] - if missing: - raise AssertionError( - f"{context} critical services unhealthy: {missing} | payload={payload}" - ) - degraded = [name for name, svc_status in services.items() if svc_status == "degraded"] - if degraded: - self._log( - f"{context} warning: degraded dependencies detected: {', '.join(degraded)}" - ) - - def _log(self, message: str) -> None: - if self.verbose: - print(f"[api-flow] {message}") - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Validate taiji-AI-PAD API flows") - parser.add_argument("--data-ingestion-url", default="http://localhost:8001", help="Data Ingestion base URL") - parser.add_argument("--mcp-server-url", default="http://localhost:8002", help="MCP Server base URL") - parser.add_argument("--timeout", type=int, default=30, help="HTTP timeout in seconds") - parser.add_argument("--skip-data", action="store_true", help="Skip Data Ingestion flow") - parser.add_argument("--skip-mcp", action="store_true", help="Skip MCP flow") - parser.add_argument("--quiet", action="store_true", help="Suppress verbose logs") - return parser.parse_args() - - -def main() -> None: - args = parse_args() - config = ServiceConfig( - data_ingestion_url=args.data_ingestion_url, - mcp_server_url=args.mcp_server_url, - timeout=args.timeout, - ) - tester = ApiFlowTester(config, verbose=not args.quiet) - tester.run(skip_data_ingestion=args.skip_data, skip_mcp=args.skip_mcp) - - -if __name__ == "__main__": - try: - main() - except (AssertionError, requests.RequestException) as exc: - print(f"[api-flow] ❌ {exc}", file=sys.stderr) - sys.exit(1) - except KeyboardInterrupt: - print("[api-flow] Interrupted", file=sys.stderr) - sys.exit(130) diff --git a/services/data-ingestion/requirements.txt b/services/data-ingestion/requirements.txt index e6c6074..5d323d6 100644 --- a/services/data-ingestion/requirements.txt +++ b/services/data-ingestion/requirements.txt @@ -49,4 +49,5 @@ pytest==7.4.3 pytest-asyncio==0.21.1 black==23.11.0 flake8==6.1.0 -mypy==1.7.1 \ No newline at end of file +mypy==1.7.1 +pydantic[email] \ No newline at end of file diff --git a/services/mcp-server/DEPLOY_AZURE.md b/services/mcp-server/DEPLOY_AZURE.md index 184ffad..4aa792b 100644 --- a/services/mcp-server/DEPLOY_AZURE.md +++ b/services/mcp-server/DEPLOY_AZURE.md @@ -360,3 +360,4 @@ az group delete --name $RESOURCE_GROUP --yes Copyright © 2025 Taiji AI. All rights reserved. + diff --git a/services/mcp-server/app/billing.py b/services/mcp-server/app/billing.py index 446412b..83089d7 100644 --- a/services/mcp-server/app/billing.py +++ b/services/mcp-server/app/billing.py @@ -411,3 +411,4 @@ async def calculate_channel_commission( return total_revenue, commission + diff --git a/services/mcp-server/app/permissions.py b/services/mcp-server/app/permissions.py index a6742ce..4b738ee 100644 --- a/services/mcp-server/app/permissions.py +++ b/services/mcp-server/app/permissions.py @@ -156,3 +156,4 @@ def require_permission(required_permission: str): return wrapper return decorator + diff --git a/services/mcp-server/app/routes/admin.py b/services/mcp-server/app/routes/admin.py index 4e1f79c..7973bd3 100644 --- a/services/mcp-server/app/routes/admin.py +++ b/services/mcp-server/app/routes/admin.py @@ -593,3 +593,4 @@ async def get_billing_overview( } ) + diff --git a/services/mcp-server/app/routes/channel.py b/services/mcp-server/app/routes/channel.py index 26a1ced..f1d47d0 100644 --- a/services/mcp-server/app/routes/channel.py +++ b/services/mcp-server/app/routes/channel.py @@ -506,3 +506,4 @@ async def get_channel_billing_stats( } ) + diff --git a/services/mcp-server/app/routes/providers.py b/services/mcp-server/app/routes/providers.py index 3398830..05670dd 100644 --- a/services/mcp-server/app/routes/providers.py +++ b/services/mcp-server/app/routes/providers.py @@ -275,3 +275,4 @@ async def test_model_provider( } ) + diff --git a/services/mcp-server/app/routes/user.py b/services/mcp-server/app/routes/user.py index a63fc95..20a442d 100644 --- a/services/mcp-server/app/routes/user.py +++ b/services/mcp-server/app/routes/user.py @@ -561,3 +561,4 @@ async def get_billing_history( } ) + diff --git a/services/mcp-server/database.py b/services/mcp-server/database.py index 768d7af..48ae970 100644 --- a/services/mcp-server/database.py +++ b/services/mcp-server/database.py @@ -76,10 +76,13 @@ async def init_db(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) - logger.info("数据库初始化成功") + logger.info("数据库表创建成功") - # 创建初始数据 - await create_initial_data() + # 尝试创建初始数据,失败不阻止启动 + try: + await create_initial_data() + except Exception as init_err: + logger.warning(f"创建初始数据失败(服务将继续启动): {init_err}") except Exception as e: logger.error(f"数据库初始化失败: {e}") diff --git a/services/mcp-server/k8s/deployment.yaml b/services/mcp-server/k8s/deployment.yaml index 639ef8a..e4960fd 100644 --- a/services/mcp-server/k8s/deployment.yaml +++ b/services/mcp-server/k8s/deployment.yaml @@ -186,3 +186,4 @@ spec: matchLabels: app: mcp-server + diff --git a/services/mcp-server/k8s/ingress.yaml b/services/mcp-server/k8s/ingress.yaml index 373c593..c640ff9 100644 --- a/services/mcp-server/k8s/ingress.yaml +++ b/services/mcp-server/k8s/ingress.yaml @@ -64,3 +64,4 @@ metadata: name: taiji-ai environment: production + diff --git a/services/mcp-server/k8s/secrets.yaml b/services/mcp-server/k8s/secrets.yaml index 1ff4840..3f8dd31 100644 --- a/services/mcp-server/k8s/secrets.yaml +++ b/services/mcp-server/k8s/secrets.yaml @@ -43,3 +43,4 @@ data: # --docker-password=${SP_PASSWORD} \ # --namespace=taiji-ai + diff --git a/services/mcp-server/models.py b/services/mcp-server/models.py index 80ea982..9ecf484 100644 --- a/services/mcp-server/models.py +++ b/services/mcp-server/models.py @@ -400,6 +400,51 @@ class APIKey(BaseModel, Base): ) +class Billing(BaseModel, Base): + """计费详情模型(按执行记录计费)""" + __tablename__ = "billing" + + execution_id = Column(GUID(), ForeignKey("executions.id"), nullable=False) + eu_consumed = Column(sa.Float, nullable=False, default=0.0) + cost = Column(sa.Float, nullable=False, default=0.0) + currency = Column(String(10), default="EU") + + # 资源使用详情 + cpu_time = Column(sa.Float, default=0.0) + memory_max = Column(sa.Float, default=0.0) + network_io = Column(sa.Float, default=0.0) + storage_io = Column(sa.Float, default=0.0) + + user_id = Column(GUID(), ForeignKey("users.id"), nullable=False) + + # 关联关系 + user = relationship("User") + execution = relationship("Execution") + + # 索引 + __table_args__ = ( + Index("idx_billing_execution", execution_id), + Index("idx_billing_user", user_id), + Index("idx_billing_created", "created_at"), + ) + + +class Balance(BaseModel, Base): + """用户余额模型""" + __tablename__ = "balances" + + user_id = Column(GUID(), ForeignKey("users.id"), nullable=False, unique=True) + eu_balance = Column(sa.Float, nullable=False, default=0.0) + + # 关联关系 + user = relationship("User") + + # 索引 + __table_args__ = ( + Index("idx_balance_user", user_id), + ) + + class BillingRecord(BaseModel, Base): """计费记录模型""" __tablename__ = "billing_records" @@ -531,3 +576,45 @@ class AuditLog(BaseModel, Base): Index("idx_audit_created", "created_at"), ) + +class ChannelAgentQuota(BaseModel, Base): + """渠道Agent配额模型""" + __tablename__ = "channel_agent_quotas" + + channel_id = Column(GUID(), ForeignKey("channels.id"), nullable=False) + agent_id = Column(GUID(), ForeignKey("agents.id"), nullable=False) + quantity = Column(Integer, nullable=False, default=0) + + # 关联关系 + channel = relationship("Channel") + agent = relationship("Agent") + + # 索引 + __table_args__ = ( + Index("idx_channel_agent_quota_channel", channel_id), + Index("idx_channel_agent_quota_agent", agent_id), + UniqueConstraint("channel_id", "agent_id", name="uq_channel_agent"), + ) + + +class ProviderModel(BaseModel, Base): + """模型提供商模型(前端集成使用)""" + __tablename__ = "provider_models" + + name = Column(String(100), nullable=False) + api_url = Column(String(500), nullable=False) + api_key = Column(Text, nullable=False) + supported_models = Column(JSON, default=list) + rpm = Column(Integer, default=0) + tpm = Column(Integer, default=0) + status = Column(String(20), default="active") + + # 索引 + __table_args__ = ( + Index("idx_provider_model_name", name), + ) + + +# 别名:Tenant 指向 User(租户即为user) +Tenant = User + diff --git a/services/mcp-server/requirements-test.txt b/services/mcp-server/requirements-test.txt deleted file mode 100644 index 07e39e1..0000000 --- a/services/mcp-server/requirements-test.txt +++ /dev/null @@ -1,22 +0,0 @@ -# 测试依赖 - -# 核心测试框架 -pytest==7.4.3 -pytest-asyncio==0.21.1 -pytest-cov==4.1.0 - -# HTTP测试 -httpx==0.25.2 - -# 数据库测试 -aiosqlite==0.19.0 - -# Mock和Fixture -pytest-mock==3.12.0 -faker==20.1.0 - -# 代码质量 -flake8==6.1.0 -black==23.12.1 -mypy==1.7.1 - diff --git a/services/mcp-server/requirements.txt b/services/mcp-server/requirements.txt index 92406c4..0322a0b 100644 --- a/services/mcp-server/requirements.txt +++ b/services/mcp-server/requirements.txt @@ -22,6 +22,9 @@ cryptography==42.0.0 redis==5.0.1 hiredis==2.3.2 +# NATS +nats-py==2.6.0 + # HTTP客户端 httpx==0.26.0 aiohttp==3.9.1 @@ -32,7 +35,10 @@ email-validator==2.1.0 # 监控和日志 prometheus-client==0.19.0 +structlog==24.1.0 +psutil==5.9.8 # 其他 Jinja2==3.1.3 MarkupSafe==2.1.3 +pydantic[email] \ No newline at end of file diff --git a/services/mcp-server/scripts/check_accounts.py b/services/mcp-server/scripts/check_accounts.py index 60e1597..d81bf80 100644 --- a/services/mcp-server/scripts/check_accounts.py +++ b/services/mcp-server/scripts/check_accounts.py @@ -169,3 +169,4 @@ if __name__ == "__main__": success = main() exit(0 if success else 1) + diff --git a/services/mcp-server/scripts/deploy-azure.sh b/services/mcp-server/scripts/deploy-azure.sh index 68693bd..f09d9fd 100644 --- a/services/mcp-server/scripts/deploy-azure.sh +++ b/services/mcp-server/scripts/deploy-azure.sh @@ -144,3 +144,4 @@ echo "kubectl get all -n $NAMESPACE" echo -e "\n${GREEN}部署成功!${NC}" + diff --git a/services/mcp-server/scripts/run_tests.sh b/services/mcp-server/scripts/run_tests.sh index fa82ee6..a869d96 100755 --- a/services/mcp-server/scripts/run_tests.sh +++ b/services/mcp-server/scripts/run_tests.sh @@ -72,3 +72,4 @@ echo "==========================================" echo "测试完成!" echo "==========================================" + diff --git a/services/mcp-server/tests/__init__.py b/services/mcp-server/tests/__init__.py index b15e0bb..edb7324 100644 --- a/services/mcp-server/tests/__init__.py +++ b/services/mcp-server/tests/__init__.py @@ -2,3 +2,4 @@ 测试模块初始化文件 """ + diff --git a/services/mcp-server/tests/conftest.py b/services/mcp-server/tests/conftest.py index 1977164..bbf4519 100644 --- a/services/mcp-server/tests/conftest.py +++ b/services/mcp-server/tests/conftest.py @@ -242,3 +242,4 @@ def auth_headers(): return {"Authorization": f"Bearer {token}"} return _auth_headers + diff --git a/services/mcp-server/tests/test_api_endpoints.py b/services/mcp-server/tests/test_api_endpoints.py index d75d216..640eda2 100644 --- a/services/mcp-server/tests/test_api_endpoints.py +++ b/services/mcp-server/tests/test_api_endpoints.py @@ -328,3 +328,4 @@ class TestHealthCheck: if __name__ == "__main__": pytest.main([__file__, "-v"]) + diff --git a/services/mcp-server/tests/test_permissions.py b/services/mcp-server/tests/test_permissions.py index 463ebdf..599c38c 100644 --- a/services/mcp-server/tests/test_permissions.py +++ b/services/mcp-server/tests/test_permissions.py @@ -487,3 +487,4 @@ class TestPermissionInheritance: if __name__ == "__main__": pytest.main([__file__, "-v"]) + diff --git a/test_apillama_fix.py b/test_apillama_fix.py index 19c5a75..859edab 100644 --- a/test_apillama_fix.py +++ b/test_apillama_fix.py @@ -69,3 +69,4 @@ if __name__ == "__main__": result = asyncio.run(test_extract_parameters()) sys.exit(0 if result else 1) + diff --git a/verify_apillama_fix.py b/verify_apillama_fix.py index ef6ddd8..7c8de70 100644 --- a/verify_apillama_fix.py +++ b/verify_apillama_fix.py @@ -157,3 +157,4 @@ if __name__ == "__main__": result = test_cases() sys.exit(0 if result else 1) +