feat: 添加租户管理和K8s Agent API,更新文档

This commit is contained in:
xiaohei
2025-12-31 09:11:28 +00:00
parent 8c4284d38d
commit eb2a88861b
13 changed files with 1789 additions and 5419 deletions
+125 -5
View File
@@ -87,6 +87,11 @@ export default function AdminDashboard() {
const [channelTenants, setChannelTenants] = useState<any[]>([])
const [selectedTenantForEdit, setSelectedTenantForEdit] = useState<any>(null)
const [selectedTenantForPermission, setSelectedTenantForPermission] = useState<any>(null)
// 新增:修改密码对话框状态
const [isChangePasswordDialogOpen, setIsChangePasswordDialogOpen] = useState(false)
const [newPassword, setNewPassword] = useState("")
const [confirmPassword, setConfirmPassword] = useState("")
const [changePasswordLoading, setChangePasswordLoading] = useState(false)
const [newTenantForm, setNewTenantForm] = useState({
name: "",
email: "",
@@ -579,10 +584,22 @@ export default function AdminDashboard() {
setAgentResources(agentResourcesData)
}
// TODO: 加载租户列表 - 需要添加对应的API方法
setTenants([])
// 加载租户列表
try {
const tenantsData = await TaijiAPIClient.getAdminTenants()
if (tenantsData?.success && tenantsData.data?.tenants) {
setTenants(tenantsData.data.tenants)
} else if (Array.isArray(tenantsData?.data)) {
setTenants(tenantsData.data)
} else {
setTenants([])
}
} catch (error) {
console.log("Failed to load tenants:", error)
setTenants([])
}
// TODO: 加载数据源列表 - 需要添加对应的API方法
// 数据源列表暂时设为空(后端API待实现)
setAvailableDataSources([])
} catch (error) {
console.error("Failed to load dashboard data:", error)
@@ -1014,8 +1031,43 @@ export default function AdminDashboard() {
const tenant = channelTenants.find(t => t.id === tenantId)
if (!tenant) return
setSelectedTenantForEdit(tenant)
// TODO: 打开修改密码对话框并调用 /api/channel/tenants/{tenant_id}/password
console.log("Change password for tenant:", tenantId)
setNewPassword("")
setConfirmPassword("")
setIsChangePasswordDialogOpen(true)
}
// 新增:执行密码修改
const handleConfirmChangePassword = async () => {
if (!selectedTenantForEdit) return
// 验证密码
if (!newPassword || newPassword.length < 6) {
alert(language === "zh" ? "密码长度至少6位" : "Password must be at least 6 characters")
return
}
if (newPassword !== confirmPassword) {
alert(language === "zh" ? "两次输入的密码不一致" : "Passwords do not match")
return
}
setChangePasswordLoading(true)
try {
const result = await TaijiAPIClient.changeTenantPassword(selectedTenantForEdit.id, newPassword)
if (result?.success) {
alert(language === "zh" ? "密码修改成功" : "Password changed successfully")
setIsChangePasswordDialogOpen(false)
setNewPassword("")
setConfirmPassword("")
setSelectedTenantForEdit(null)
} else {
alert(result?.message || (language === "zh" ? "密码修改失败" : "Failed to change password"))
}
} catch (error: any) {
console.error("Failed to change password:", error)
alert(error?.message || (language === "zh" ? "密码修改出错" : "Error changing password"))
} finally {
setChangePasswordLoading(false)
}
}
// 新增:删除租户
@@ -2572,6 +2624,74 @@ export default function AdminDashboard() {
</DialogContent>
</Dialog>
{/* Change Password Dialog */}
<Dialog open={isChangePasswordDialogOpen} onOpenChange={setIsChangePasswordDialogOpen}>
<DialogContent className="bg-card border-border max-w-md">
<DialogHeader>
<DialogTitle>{language === "zh" ? "修改租户密码" : "Change Tenant Password"}</DialogTitle>
<DialogDescription>
{language === "zh"
? `为租户 "${selectedTenantForEdit?.name}" 设置新密码`
: `Set a new password for tenant "${selectedTenantForEdit?.name}"`}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="new-password">{language === "zh" ? "新密码" : "New Password"}</Label>
<Input
id="new-password"
type="password"
placeholder={language === "zh" ? "输入新密码(至少6位)" : "Enter new password (min 6 chars)"}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="bg-background"
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirm-password">{language === "zh" ? "确认密码" : "Confirm Password"}</Label>
<Input
id="confirm-password"
type="password"
placeholder={language === "zh" ? "再次输入新密码" : "Re-enter new password"}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="bg-background"
/>
</div>
{newPassword && confirmPassword && newPassword !== confirmPassword && (
<p className="text-sm text-destructive">
{language === "zh" ? "两次输入的密码不一致" : "Passwords do not match"}
</p>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setIsChangePasswordDialogOpen(false)
setNewPassword("")
setConfirmPassword("")
}}
>
{language === "zh" ? "取消" : "Cancel"}
</Button>
<Button
className="bg-primary text-primary-foreground"
onClick={handleConfirmChangePassword}
disabled={changePasswordLoading || !newPassword || newPassword !== confirmPassword}
>
{changePasswordLoading
? (language === "zh" ? "修改中..." : "Changing...")
: (language === "zh" ? "确认修改" : "Confirm Change")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<div className="mt-8">
<h3 className="text-lg font-semibold mb-4">
{language === "zh" ? "渠道申请审批" : "Channel Application Approvals"}
+6 -6
View File
@@ -42,9 +42,9 @@ export default function OrchestrationPage() {
try {
setLoading(true)
// 并行加载Agent列表和工作流列表
const [agentsResult] = await Promise.allSettled([
const [agentsResult, workflowsResult] = await Promise.allSettled([
TaijiAPIClient.getPlatformAgents(),
// TODO: 添加获取工作流列表的API调用
TaijiAPIClient.getWorkflows(),
])
// 加载平台Agent列表
@@ -54,10 +54,10 @@ export default function OrchestrationPage() {
}
// 加载工作流列表
// TODO: 当后端API可用时,取消注释
// if (workflowsResult.status === "fulfilled" && workflowsResult.value?.success) {
// setWorkflows(workflowsResult.value.data || [])
// }
if (workflowsResult.status === "fulfilled" && workflowsResult.value?.success) {
const data = workflowsResult.value.data?.data || workflowsResult.value.data || []
setWorkflows(data)
}
} catch (error) {
console.error("Failed to load data:", error)
} finally {
-219
View File
@@ -1,219 +0,0 @@
# Taiji AI PAD 前端 API 接口状态文档
**更新时间**: 2025年1月
**前端项目**: taiji-pad-v0
**后端服务**:
- MCP Server: `http://localhost:8002`
- Data Ingestion: `http://localhost:8001`
---
## 📊 总体状态
| 模块 | 接口数量 | 状态 |
|------|----------|------|
| 认证模块 | 6 | ✅ 全部已实现 |
| 用户侧平台 | 14 | ✅ 全部已实现 |
| 渠道合作伙伴 | 8 | ✅ 全部已实现 |
| 超级管理员 | 12 | ✅ 全部已实现 |
| 供应商管理 | 6 | ✅ 全部已实现 |
| Data Ingestion | 12 | ✅ 全部已实现 |
| MCP Server 核心 | 7 | ✅ 全部已实现 |
| 监控 API | 5 | ✅ 全部已实现 |
| WebSocket | 1 | ✅ 已实现 |
| **总计** | **71** | **✅ 全部已实现** |
---
## ✅ API 接口清单
### 1. 认证模块 API (`/api/auth`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 用户登录 | POST | `/api/auth/login` | ✅ | 支持多角色登录 |
| 用户登出 | POST | `/api/auth/logout` | ✅ | 清除token |
| 刷新Token | POST | `/api/auth/refresh` | ✅ | 刷新访问令牌 |
| 修改密码 | PUT | `/api/auth/password` | ✅ | 修改用户密码 |
| 获取API密钥信息 | GET | `/api/auth/keys/info` | ✅ | 获取当前用户API密钥 |
| 重新生成API密钥 | POST | `/api/auth/keys/regenerate` | ✅ | 重新生成API密钥 |
---
### 2. 用户侧平台 API (`/api/user`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 获取仪表板统计 | GET | `/api/user/dashboard/stats` | ✅ | 概览数据 |
| 获取Agent活动数据 | GET | `/api/user/agents/activity` | ✅ | 支持7d/30d/90d周期 |
| 选择网关类型 | POST | `/api/user/gateway/select` | ✅ | MCP/A2A/API |
| 创建网关API | POST | `/api/user/gateway/api/create` | ✅ | 创建自定义API |
| 获取网关API列表 | GET | `/api/user/gateway/apis` | ✅ | 列表查询 |
| 获取网关监控数据 | GET | `/api/user/gateway/monitoring` | ✅ | 监控信息 |
| 生成工具 | POST | `/api/user/tools/generate` | ✅ | 工具生成 |
| 创建数据模板 | POST | `/api/user/data-templates/create` | ✅ | JSON API/云存储 |
| 获取平台Agent列表 | GET | `/api/user/agents/platform` | ✅ | 平台Agent |
| 部署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` | ✅ | 支持导出 |
---
### 3. 渠道合作伙伴 API (`/api/channel`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 获取租户列表 | GET | `/api/channel/tenants` | ✅ | 渠道下租户 |
| 创建租户 | POST | `/api/channel/tenants/create` | ✅ | 创建新租户 |
| 分配租户资源 | PUT | `/api/channel/tenants/{id}/resources` | ✅ | Agent/模型资源 |
| 更新租户计费设置 | 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` | ✅ | 支持导出 |
---
### 4. 超级管理员 API (`/api/admin`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 获取平台统计 | GET | `/api/admin/dashboard/stats` | ✅ | 平台总览 |
| 创建管理员 | POST | `/api/admin/admins/create` | ✅ | 计费/运营管理员 |
| 获取渠道列表 | 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` | ✅ | 模型供应商列表 |
| 获取Agent资源 | GET | `/api/admin/resources/agents` | ✅ | Agent资源列表 |
| 删除Agent资源 | DELETE | `/api/admin/resources/agents/{id}` | ✅ | 删除Agent |
| 监控Agent健康 | GET | `/api/admin/monitoring/agents` | ✅ | Agent监控 |
| 获取计费概览 | GET | `/api/admin/billing/overview` | ✅ | 三维度计费 |
---
### 5. 供应商管理 API (`/api/providers`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 获取模型供应商列表 | 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` | ✅ | 连接测试 |
---
### 6. Data Ingestion 服务 API (`:8001`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 健康检查 | GET | `/health` | ✅ | 服务状态 |
| 同步RapidAPI | POST | `/rapidapi/sync` | ✅ | 后台同步 |
| 测试RapidAPI | POST | `/rapidapi/test` | ✅ | 端点测试 |
| 解析OpenAPI | POST | `/openapi/parse` | ✅ | OpenAPI解析 |
| APILLAMA处理 | POST | `/apillama/process` | ✅ | API文档处理 |
| 生成工具定义 | POST | `/tools/generate` | ✅ | 工具生成 |
| 获取工具列表 | GET | `/tools` | ✅ | 工具查询 |
| 获取工具定义 | GET | `/tools/{name}` | ✅ | 工具详情 |
| 删除工具 | DELETE | `/tools/{name}` | ✅ | 工具删除 |
| 获取统计信息 | GET | `/stats` | ✅ | 统计数据 |
| 清除缓存 | POST | `/cache/clear` | ✅ | 清理缓存 |
| Prometheus Metrics | GET | `/metrics` | ✅ | 监控指标 |
---
### 7. MCP Server 服务 API (`:8002`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 健康检查 | GET | `/health` | ✅ | 服务状态 |
| 注册Agent | POST | `/agents` | ✅ | 新建Agent |
| 获取Agent列表 | GET | `/agents` | ✅ | Agent列表 |
| 获取Agent详情 | GET | `/agents/{id}` | ✅ | Agent详情 |
| 执行Agent工具 | POST | `/agents/{id}/execute` | ✅ | 工具执行 |
| 获取工具列表 | GET | `/tools` | ✅ | MCP工具列表 |
| Prometheus Metrics | GET | `/metrics` | ✅ | 监控指标 |
---
### 8. MCP 监控 API (`/api/v1/monitoring`)
| 接口 | 方法 | 路径 | 状态 | 说明 |
|------|------|------|------|------|
| 获取系统性能指标 | GET | `/api/v1/monitoring/metrics` | ✅ | CPU/内存/磁盘 |
| 获取服务统计 | GET | `/api/v1/monitoring/stats` | ✅ | 按服务聚合 |
| 获取性能趋势 | GET | `/api/v1/monitoring/trends` | ✅ | 时间区间趋势 |
| 获取系统告警 | GET | `/api/v1/monitoring/alerts` | ✅ | 告警列表 |
| 获取监控仪表盘 | GET | `/api/v1/monitoring/dashboard` | ✅ | 聚合数据 |
---
### 9. WebSocket API
| 接口 | 路径 | 状态 | 说明 |
|------|------|------|------|
| Agent WebSocket | `ws://localhost:8002/ws/{agent_id}` | ✅ | 实时通信 |
---
## 🧹 前端假数据清理记录
已删除以下硬编码的假数据,前端现在仅使用 API 返回的真实数据:
### 1. agent-factory/page.tsx
- ❌ 删除 `defaultPlatformAgents` 数组(包含6个假Agent:天气查询、数据分析、文档处理、邮件管理、API集成、数据库操作)
- ✅ 页面现在仅显示从 `/api/user/agents/platform` 获取的真实数据
- ✅ 无数据时显示空状态提示
### 2. model-gateway/page.tsx
- ❌ 删除 `defaultFrameworks` 数组中的假统计数据(endpoints: 8/5/6, usage: 42%/28%/30%)
- ✅ 保留网关类型定义(MCP/A2A/API)作为系统固定选项(非假数据)
- ✅ 移除了"网关使用分布"假图表
### 3. orchestration/page.tsx
- ❌ 删除 `defaultAvailableAgents` 数组(包含8个假Agent)
- ✅ 页面现在仅显示从 `/api/user/agents/platform` 获取的真实数据
- ✅ 无数据时显示空状态提示
### 4. data-tools/page.tsx
- ❌ 删除硬编码的 "3个已配置" 和 "5个已配置" Badge标签
---
## 🔧 角色权限映射
| 前端角色 | 后端role参数 | 登录入口 |
|----------|-------------|----------|
| 超级管理员 | `super_admin` | `/admin/login` |
| 计费管理员 | `billing_admin` | `/admin/login` |
| 运营管理员 | `operations_admin` | `/admin/login` |
| 渠道管理员 | `channel` | `/channel/login` |
| 租户用户 | `user` | `/login` |
---
## 📌 注意事项
1. **认证方式**: 所有需认证接口支持 `Authorization: Bearer <token>` 或 `X-API-Key: <api_key>`
2. **角色映射**: 前端系统权限与后端订阅级别映射
- `tenant` → `free`
- `admin` → `pro`
- `billing-admin` → `enterprise`
- `operations-admin` → `enterprise`
3. **数据空值处理**: 前端对返回数据做空值检查(如 `capabilities || []`)
4. **空状态显示**: 当 API 无返回数据时,前端显示友好的空状态提示,不再使用假数据回退
---
## 📅 更新日志
- **2025-01**: 清理前端所有假数据,确保页面仅使用 API 真实数据
- **2025-12-26**: 初始版本,整理71个已完成接口
-69
View File
@@ -1,69 +0,0 @@
# Azure Static Web Apps 部署指南
## 已应用的 Azure 最佳实践
### 1. Next.js 配置 (`next.config.mjs`)
- ✅ **Standalone 输出模式**: `output: 'standalone'` 生成独立部署包
- ✅ **环境变量配置**: 明确声明 `NEXT_PUBLIC_*` 环境变量
- ✅ **图片优化**: `unoptimized: true` 适配 Azure SWA
- ✅ **TypeScript 编译**: 保留现有业务逻辑,忽略构建错误便于快速部署
### 2. 静态 Web 应用配置 (`staticwebapp.config.json`)
- ✅ **路由回退**: 所有路由回退到 `/index.html` 以支持 Next.js 客户端路由
- ✅ **平台设置**: 明确指定 `node:20` 运行时
- ✅ **文件排除**: 正确排除 `_next/*`、`static/*` 等静态资源
- ✅ **404 处理**: 配置为 200 状态码重写,避免 SPA 路由问题
- ✅ **MIME 类型**: 明确 `.js`、`.css`、`.json` 的 Content-Type
### 3. GitHub Actions 工作流
- ✅ **Node 版本**: 固定 20.11.1 与本地一致
- ✅ **NPM 缓存**: 使用 `cache: 'npm'` 加速依赖安装
- ✅ **环境变量**: 构建时注入 `NEXT_PUBLIC_*` 秘钥
- ✅ **输出目录**: `output_location: '.next/standalone'` 对齐 Next.js standalone 模式
- ✅ **跳过重复构建**: `skip_app_build: true` 避免 SWA Oryx 重复构建
### 4. 环境变量管理
创建了 `.env.example` 模板,需要在 GitHub Secrets 中配置:
- `NEXT_PUBLIC_DATA_INGESTION_URL`
- `NEXT_PUBLIC_MCP_SERVER_URL`
- `NEXT_PUBLIC_API_GATEWAY_URL`
- `AZURE_STATIC_WEB_APPS_API_TOKEN`
### 5. 业务逻辑保留
- ✅ 所有 API 客户端代码 (`lib/api-client.ts`) 保持不变
- ✅ 认证流程 (`lib/auth.ts`、服务端 `layout.tsx`) 完整保留
- ✅ 页面组件、UI 组件、上下文逻辑全部保持原样
- ✅ 重定向规则 (`/admin` → `/admin/dashboard`) 继续生效
## 部署步骤
### 配置 GitHub Secrets
1. 进入仓库 **Settings** → **Secrets and variables** → **Actions**
2. 添加以下 Secrets:
```
AZURE_STATIC_WEB_APPS_API_TOKEN=<从 Azure Portal 获取>
NEXT_PUBLIC_DATA_INGESTION_URL=http://135.171.216.9/api/data-ingestion
NEXT_PUBLIC_MCP_SERVER_URL=http://135.171.216.9/api/mcp
NEXT_PUBLIC_API_GATEWAY_URL=http://135.171.216.9/api
```
### 触发部署
- **自动**: 推送到 `gzy` 分支
- **手动**: Actions → Azure Static Web Apps CI/CD → Run workflow
## 验证构建
本地验证已通过:
```bash
npm run build
# ✓ Compiled successfully
# ✓ Standalone build exists at .next/standalone
```
## 故障排查
- **routes.json 冲突**: 已解决,使用 `staticwebapp.config.json` 替代
- **构建产物路径**: 已修正为 `.next/standalone`
- **环境变量**: 通过 GitHub Secrets 注入,避免硬编码
- **Node 版本**: 工作流、.nvmrc、package.json 三处统一为 20.11.1
## 下一步
监控 GitHub Actions 运行结果,确认 Azure SWA 部署成功且应用功能正常。
File diff suppressed because it is too large Load Diff
-434
View File
@@ -1,434 +0,0 @@
# Taiji AI Platform 业务逻辑分析文档
## 📋 项目概述
**项目名称**: Taiji AI Platform(太极AI平台)
**项目性质**: 企业级AI Agent编排和管理平台
**核心功能**: 提供多租户AI Agent部署、资源管理、计费统计、渠道合作等功能
---
## 🏗️ 系统架构
### 整体架构
```
┌─────────────────────────────────────────────────────────────┐
│ 前端应用 (Next.js) │
│ taiji-pad-v0 (TypeScript/React) │
└────────────────┬────────────────────────────────────────────┘
│
┌────────────┼────────────┬──────────────┐
│ │ │ │
v v v v
┌────────┐ ┌────────────┐ ┌────────────┐ ┌──────────┐
│MCP内核 │ │数据接入处理│ │LiteLLM网关 │ │PostgreSQL│
│Server │ │ 服务 │ │(模型编排) │ │数据库 │
└────────┘ └────────────┘ └────────────┘ └──────────┘
8002 8001 4000 5432
```
### 核心服务
1. **MCP Server** (8002) - 核心业务逻辑、认证、资源管理
2. **Data Ingestion** (8001) - API集成、工具生成
3. **LiteLLM Gateway** (4000) - 模型网关、请求路由
4. **PostgreSQL** - 数据持久化存储
---
## 👥 用户角色与权限体系
### 用户角色分类
```
┌──────────────────────────────────────────────────────┐
│ 系统用户角色分层体系 │
├──────────────────────────────────────────────────────┤
│ 超级管理员 (Super Admin) │
│ └─ 权限: 平台全局管理、所有统计数据、审批所有申请 │
│ └─ 路径: /admin/dashboard │
│ │
│ 管理员角色(渠道内) │
│ ├─ 计费管理员 (Billing Admin) │
│ │ └─ 权限: 计费、充值、订阅管理 │
│ ├─ 运营管理员 (Operations Admin) │
│ │ └─ 权限: 资源分配、Agent管理 │
│ │ │
│ 渠道管理员 (Channel Admin) │
│ └─ 权限: 渠道下租户管理、资源分配、申请管理 │
│ └─ 路径: /channel/dashboard │
│ │
│ 普通用户 (User / Tenant) │
│ └─ 权限: 个人Agent部署、工具生成、计费查询 │
│ └─ 路径: / (首页) │
│ │
│ 模型供应商 (Provider) │
│ └─ 权限: 供应商资源申请和管理 │
└──────────────────────────────────────────────────────┘
```
### 权限矩阵
| 角色 | 用户管理 | Agent管理 | 计费管理 | 资源审批 | 渠道管理 | 供应商管理 |
|------|--------|---------|--------|--------|--------|----------|
| 超级管理员 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 渠道管理员 | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ |
| 计费管理员 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
| 运营管理员 | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
| 普通用户 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
---
## 📊 核心业务模块
### 1. 认证与授权模块 (`/api/auth`)
**功能说明**:
- 支持多角色用户登录(普通用户、渠道管理员、超级管理员、供应商等)
- JWT Token认证机制
- API密钥管理(用于API调用)
- Token刷新和密码管理
**关键流程**:
```
用户登录 → Token生成 → 存储本地 → 验证权限 → 访问受保护资源
```
**实现细节**:
- Token存储在 localStorage(区分 auth_token/admin_token/channel_token)
- 支持 Bearer Token 和 API Key 两种认证方式
- 自动重定向到对应登录页面(/login, /admin/login, /channel/login)
---
### 2. 用户侧平台模块 (`/api/user`)
**功能说明**: 普通租户用户的自助服务平台
#### 2.1 Agent管理
- **获取平台Agent列表**: 查看所有可用的预置Agent
- **部署Agent**: 部署Agent实例到指定网关
- **自定义Agent**: 创建和配置自定义Agent
**数据流**:
```
平台Agent → 选择实例数/模型 → 部署配置 → 执行部署 → 获得运行实例
```
**关键参数**:
- `instances`: Agent实例数(基于资源分配)
- `model`: 使用的模型(gpt-4o-mini, gpt-4等)
- `gateway`: 执行网关(MCP/A2A/API)
#### 2.2 服务网关管理
三种网关类型:
- **MCP (Model Context Protocol)**: 标准MCP协议,支持工具定义
- **A2A (Agent-to-Agent)**: Agent间协作,用于编排
- **API**: 暴露HTTP API供外部调用
#### 2.3 数据与工具
- **生成工具**: 通过框架模板生成可复用工具
- **创建数据模板**: JSON API或云存储配置
#### 2.4 工作流编排
- **创建工作流**: 串联多个Agent(最多3个节点)
- **执行工作流**: 按顺序执行Agent链
#### 2.5 计费与充值
- **查看余额**: 账户余额和月度消耗
- **充值**: 支付宝/微信/卡支付
- **计费历史**: 查询和导出使用记录
---
### 3. 渠道合作伙伴模块 (`/api/channel`)
**功能说明**: 渠道管理员管理其下属租户
#### 3.1 租户管理
- **创建租户**: 为企业客户创建账户
- **分配资源**: 给租户分配Agent和模型额度
- **管理计费**: 设置订阅级别、折扣、授信额度
- **充值**: 代客户充值
**租户生命周期**:
```
创建 → 分配资源 → 分配模型 → 启用使用 → 计费结算
```
#### 3.2 供应商管理
- **申请资源**: 申请使用模型供应商或Agent资源
- **查看申请**: 监控所有资源申请状态
- **获取供应商列表**: 了解可用的供应商
#### 3.3 计费统计
- **按租户统计**: 每个租户的消费数据
- **导出报表**: Excel/CSV/PDF格式
---
### 4. 超级管理员模块 (`/api/admin`)
**功能说明**: 平台级别的管理和控制
#### 4.1 渠道管理
- **创建/编辑/删除渠道**: 管理渠道伙伴
- **分配渠道资源**: 统一分配模型和Agent额度
- **设置手续费**: 配置渠道佣金比例
#### 4.2 资源管理
- **Agent资源**: 查看和管理所有Agent
- **模型供应商**: 查看所有可用模型
- **审批申请**: 批准/拒绝资源申请
#### 4.3 监控与统计
- **平台统计**: 总用户数、总消耗、活跃Agent等
- **Agent监控**: 实时健康状态
- **计费总览**: 三个维度的计费数据
- 按渠道
- 按租户
- 按Agent类型
---
### 5. 供应商管理模块 (`/api/providers`)
**功能说明**: 模型和API供应商的接入和管理
**供应商类型**:
- **模型供应商**: OpenAI、Claude等
- **API供应商**: RapidAPI等
- **Agent提供者**: 预置Agent库
**供应商流程**:
```
供应商注册 → API接入 → 模型/API集成 → 指标上报 → 费用结算
```
---
## 🔄 核心数据流
### 流程1: 用户部署Agent的完整流程
```
1. 用户登录
└─> POST /api/auth/login
└─> 返回token → 存储localStorage
2. 查看可用Agent
└─> GET /api/user/agents/platform
└─> 返回平台Agent列表
3. 配置部署参数
└─> 选择Agent
└─> 设置实例数、模型、网关
4. 执行部署
└─> POST /api/user/agents/deploy
└─> {agentId, instances, model, gateway}
5. 监控执行
└─> GET /api/user/dashboard/stats
└─> 查看Agent活动数据
6. 管理生命周期
└─> 停止、更新、删除Agent
```
### 流程2: 渠道为租户分配资源的流程
```
1. 渠道管理员登录
└─> POST /api/auth/login (role=channel)
2. 创建租户
└─> POST /api/channel/tenants/create
└─> {name, email, systemRole, subscriptionTier}
3. 分配Agent资源
└─> PUT /api/channel/tenants/{tenantId}/resources
└─> {agents: [{agentId, quantity}]}
4. 分配模型额度
└─> PUT /api/channel/tenants/{tenantId}/resources
└─> {models: [modelNames], rpm, tpm}
5. 设置计费参数
└─> PUT /api/channel/tenants/{tenantId}/billing
└─> {subscriptionTier, discount}
6. 可选:充值
└─> POST /api/channel/tenants/{tenantId}/recharge
└─> {amount}
```
### 流程3: 超级管理员审批资源申请的流程
```
1. 管理员登录
└─> POST /api/auth/login (role=admin)
2. 查看所有申请
└─> GET /api/admin/channels/applications
3. 审批申请
└─> PUT /api/admin/channels/applications/{appId}/review
└─> {action: 'approve'|'reject', reason}
4. 分配渠道资源
└─> PUT /api/admin/channels/{channelId}/resources
└─> 为渠道分配额度
```
---
## 💾 数据模型关系
```
┌─────────────┐
│ User │ 核心用户
├─────────────┤
│ id (UUID) │
│ email │ 唯一标识
│ role │ 用户角色
│ channel_id │ 所属渠道
│ permissions │ 权限列表
└──────┬──────┘
│
├─────────────┬──────────────┬──────────────┐
│ │ │ │
v v v v
┌────────┐ ┌─────────┐ ┌─────────┐ ┌──────────┐
│ Agent │ │ Session │ │ APIKey │ │Workflow │
│(所有者)│ │ │ │ │ │ │
└────────┘ └─────────┘ └─────────┘ └──────────┘
┌─────────────┐
│ Channel │ 渠道伙伴
├─────────────┤
│ id │
│ name │
│ commission │ 手续费率
└──────┬──────┘
│
v
┌────────────┐
│ Tenant │ 租户(渠道下的客户)
│(多个User) │
└────────────┘
┌─────────────┐
│ Agent │ AI代理
├─────────────┤
│ id │
│ type │ platform/custom
│ owner_id │ 创建者
│ config │ 配置
│ tools │ 可用工具
└──────┬──────┘
│
├──────────────┬──────────────┐
│ │ │
v v v
┌─────────┐ ┌──────────┐ ┌──────────────┐
│Tool │ │Execution │ │ResourceAlloc │
│(可用工具) │ │(执行记录) │ │(资源分配) │
└─────────┘ └──────────┘ └──────────────┘
┌──────────────┐
│ GatewayAPI │ 服务网关API
├──────────────┤
│ id │
│ name │
│ type │ json/url
│ owner_id │
└──────────────┘
```
---
## 💰 计费模型
### 计费维度
1. **按使用量**: EU (Energy Unit) - 统一计费单位
2. **按订阅级别**:
- Free: 基础免费
- Pro: 中级订阅
- Enterprise: 企业订阅
3. **按渠道**: 渠道手续费
### 计费对象
- Agent执行次数
- 模型API调用 (rpm/tpm限制)
- 工具调用
- 存储容量
### 余额结构
```
账户余额 = 充值余额 + 赠送额度 - 已消耗
```
---
## 🔒 安全性设计
### 认证机制
- JWT Token + 刷新机制
- API Key for 程序化访问
- 支持多角色同时登录(不同token隔离)
### 权限控制
- 细粒度权限列表(permissions JSON)
- 基于角色的访问控制 (RBAC)
- 路由级别的认证守卫
### 数据隔离
- 租户数据隔离
- 渠道数据隔离
- 用户数据隔离
---
## 🎯 前端主要页面与功能映射
| 页面路径 | 用户角色 | 主要功能 | 依赖API |
|---------|--------|--------|--------|
| `/` | 普通用户 | 仪表板概览、快速操作 | dashboard/stats |
| `/login` | 所有人 | 用户登录 | auth/login |
| `/agent-factory` | 普通用户 | Agent部署和管理 | agents/* |
| `/data-tools` | 普通用户 | 工具生成和管理 | tools/*, data-templates/* |
| `/model-gateway` | 普通用户 | 网关选择和配置 | gateway/* |
| `/orchestration` | 普通用户 | 工作流创建和执行 | workflows/* |
| `/billing` | 普通用户 | 计费统计和充值 | billing/* |
| `/channel/dashboard` | 渠道管理员 | 租户管理、资源分配 | channel/*, admin/* |
| `/admin/dashboard` | 超级管理员 | 平台管理、审批申请 | admin/* |
---
## ⚠️ 已知问题与改进点
### 代码问题
1. ❌ **Agent删除接口混淆**: 前端使用 `deleteTool()` 删除Agent,逻辑错误
2. ❌ **缺失API**:
- 删除渠道接口
- 更新渠道信息接口
- 工作流相关的完整CRUD接口
3. ⚠️ **状态管理**: 前端缺乏全局状态管理(Redux/Zustand),大量重复的API调用
### 架构建议
1. ✅ 统一错误处理和日志记录
2. ✅ 实现请求拦截器处理token自动刷新
3. ✅ 添加request/response中间件进行参数转换
4. ✅ 前端分离API层和业务逻辑层
5. ✅ 添加乐观更新机制提升用户体验
---
## 📝 总结
该平台是一个**多层次、多角色的AI Agent管理平台**:
- **核心价值**: 降低AI Agent部署和管理的门槛
- **商业模式**: B2B2C(平台 → 渠道 → 租户)三层架构
- **盈利点**: Agent执行费用、模型API费用、订阅费用、渠道手续费
- **技术栈**: Next.js + FastAPI + PostgreSQL + LiteLLM
+703
View File
@@ -0,0 +1,703 @@
# 前后端参数对比分析报告
**生成时间**: 2025-12-31
**分析范围**: taiji-pad-v0 前端项目 vs taiji-AI-PAD 后端API文档
---
## 📋 执行摘要
本报告深入分析了前端项目 `taiji-pad-v0` 与后端API文档 `taiji-AI-PAD/Docs/前后端调试接口说明` 之间的参数匹配情况。通过逐一对比每个API接口的请求参数、响应数据结构,找出了以下问题:
### 🔴 关键发现
| 问题类型 | 数量 | 严重程度 |
|---------|------|---------|
| 参数名称不匹配 | 3 | 高 |
| 响应数据结构不一致 | 5 | 高 |
| 前端缺少必需参数 | 2 | 中 |
| 前端使用硬编码数据 | 4 | 中 |
| 接口路径不一致 | 1 | 低 |
---
## 🔍 详细分析
### 1. 认证模块 (`/api/auth`)
#### 1.1 登录接口 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/auth/login` | `POST /api/auth/login` | ✅ |
| 参数 email | string, 必需 | string | ✅ |
| 参数 password | string, 必需 | string | ✅ |
| 参数 role | string, 可选 | string | ✅ |
| 响应 token | data.token | data.token | ✅ |
#### 1.2 修改密码接口 - ⚠️ 参数名不匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `PUT /api/auth/password` | `PUT /api/auth/password` | ✅ |
| 参数 | `old_password`, `new_password` | `old_password`, `new_password` | ✅ |
**前端代码** ([`api-client.ts:245`](../lib/api-client.ts:245)):
```typescript
body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
```
---
### 2. 用户侧平台 (`/api/user`)
#### 2.1 获取仪表板统计 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `GET /api/user/dashboard/stats` | `GET /api/user/dashboard/stats` | ✅ |
| 响应 activeAgents | data.activeAgents | data.activeAgents | ✅ |
| 响应 totalRequests | data.totalRequests | data.totalRequests | ✅ |
| 响应 euBalance | data.euBalance | data.euBalance | ✅ |
| 响应 systemHealth | data.systemHealth | data.systemHealth | ✅ |
#### 2.2 获取Agent活动数据 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `GET /api/user/agents/activity` | `GET /api/user/agents/activity` | ✅ |
| 参数 period | `7d`, `30d`, `90d` | `7d`, `30d`, `90d` | ✅ |
#### 2.3 部署Agent - ⚠️ 参数类型需确认
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/user/agents/deploy` | `POST /api/user/agents/deploy` | ✅ |
| 参数 agentId | string, 必需 | string | ✅ |
| 参数 instances | int, 必需 | number | ✅ |
| 参数 model | string, 必需 | string | ✅ |
| 参数 gateway | string, 必需 | `"MCP" \| "A2A" \| "API"` | ⚠️ |
**问题**: 后端文档显示 gateway 可选值为 `MCP/LiteLLM`,但前端定义为 `MCP/A2A/API`
**后端文档**:
```
gateway (string, 必需): 网关类型 (MCP/LiteLLM)
```
**前端代码** ([`api-client.ts:410`](../lib/api-client.ts:410)):
```typescript
gateway: "MCP" | "A2A" | "API"
```
#### 2.4 创建工作流 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/user/workflows/create` | `POST /api/user/workflows/create` | ✅ |
| 参数 name | string, 必需 | string | ✅ |
| 参数 gateway | string, 必需 | `"MCP" \| "A2A" \| "API"` | ⚠️ |
| 参数 nodes | array, 必需 | array | ✅ |
---
### 3. 渠道合作伙伴 (`/api/channel`)
#### 3.1 创建租户 - 🔴 参数映射问题
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/channel/tenants/create` | `POST /api/channel/tenants/create` | ✅ |
| 参数 name | string, 必需 | string | ✅ |
| 参数 email | string, 必需 | string | ✅ |
| 参数 password | string, 必需 | string | ✅ |
| 参数 subscriptionTier | string, 可选 | 通过 systemRole 映射 | ⚠️ |
| 参数 channelId | string, 条件必需 | string, 可选 | ✅ |
**问题**: 前端使用 `systemRole` 参数,需要映射到后端的 `subscriptionTier`
**前端代码** ([`api-client.ts:522-556`](../lib/api-client.ts:522)):
```typescript
static async createChannelTenant(data: {
name: string
email: string
password: string
systemRole?: "tenant" | "admin" | "billing-admin" | "operations-admin"
subscriptionTier?: "free" | "pro" | "enterprise"
channelId?: string
}) {
// 角色到订阅等级的映射
const roleToTierMap: Record<string, string> = {
"tenant": "free",
"admin": "pro",
"billing-admin": "enterprise",
"operations-admin": "enterprise"
}
// ...
}
```
**分析**: 前端已实现映射逻辑,但 `systemRole` 的值与后端角色系统不完全对应。后端的角色是 `user`, `channel_admin`, `billing_admin`, `operations_admin`,而前端使用的是 `tenant`, `admin`, `billing-admin`, `operations-admin`。
#### 3.2 分配租户资源 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `PUT /api/channel/tenants/{tenant_id}/resources` | `PUT /api/channel/tenants/${tenantId}/resources` | ✅ |
| 参数 agents | array | array | ✅ |
| 参数 models | array | array | ✅ |
| 参数 customAgentResources | object, 可选 | object, 可选 | ✅ |
#### 3.3 申请使用供应商 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/channel/providers/apply` | `POST /api/channel/providers/apply` | ✅ |
| 参数 providerId | string, 必需 | string | ✅ |
| 参数 requestedRpm | int, 可选 | number, 可选 | ✅ |
| 参数 requestedTpm | int, 可选 | number, 可选 | ✅ |
| 参数 reason | string, 必需 | string | ✅ |
#### 3.4 禁用/启用租户 - 🔴 接口不存在于后端文档
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 禁用路径 | ❌ 未定义 | `PUT /api/channel/tenants/${tenantId}/disable` | 🔴 |
| 启用路径 | ❌ 未定义 | `PUT /api/channel/tenants/${tenantId}/enable` | 🔴 |
**问题**: 前端定义了 `disableTenant` 和 `enableTenant` 方法,但后端文档中没有这两个接口。后端只有 `updateTenantStatus` 接口。
**前端代码** ([`api-client.ts:629-646`](../lib/api-client.ts:629)):
```typescript
static async disableTenant(tenantId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/disable`, {
method: "PUT",
headers: buildHeaders(),
})
return handleResponse(response)
}
static async enableTenant(tenantId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/enable`, {
method: "PUT",
headers: buildHeaders(),
})
return handleResponse(response)
}
```
**建议**: 应使用后端的 `PUT /api/channel/tenants/{tenant_id}/status` 接口,传入 `{ status: "suspended" }` 或 `{ status: "active" }`。
---
### 4. 超级管理员 (`/api/admin`)
#### 4.1 创建管理员 - 🔴 缺少必需参数
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `POST /api/admin/admins/create` | `POST /api/admin/admins/create` | ✅ |
| 参数 name | string, 必需 | string | ✅ |
| 参数 email | string, 必需 | string | ✅ |
| 参数 password | string, 必需 | string | ✅ |
| 参数 role | string, 可选 | string | ✅ |
| 参数 channelId | string, **必需** | ❌ 未传递 | 🔴 |
**问题**: 后端文档明确指出 `channelId` 对于 `billing_admin` 和 `operations_admin` 是**必需参数**,但前端 `createAdmin` 方法没有传递此参数。
**后端文档**:
```
channelId (string, 必需): 渠道ID,指定管理员所属的渠道
重要说明: channelId 对于 billing_admin 和 operations_admin 来说是必需参数
```
**前端代码** ([`api-client.ts:807-819`](../lib/api-client.ts:807)):
```typescript
static async createAdmin(data: {
name: string
email: string
password: string
role: "billing_admin" | "operations_admin"
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/admins/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
```
**建议**: 添加 `channelId` 参数:
```typescript
static async createAdmin(data: {
name: string
email: string
password: string
role: "billing_admin" | "operations_admin"
channelId: string // 添加此参数
}) {
```
#### 4.2 更新渠道信息 - ⚠️ 参数不完整
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `PUT /api/admin/channels/{channel_id}` | `PUT /api/admin/channels/${channelId}` | ✅ |
| 参数 name | string, 可选 | string, 可选 | ✅ |
| 参数 email | string, 可选 | ❌ 未定义 | ⚠️ |
| 参数 commissionRate | float, 可选 | number, 可选 | ✅ |
| 参数 status | string, 可选 | ❌ 未定义 | ⚠️ |
| 参数 isActive | ❌ 未定义 | boolean, 可选 | ⚠️ |
**问题**: 前端使用 `isActive` 参数,但后端使用 `status` 参数。
**前端代码** ([`api-client.ts:862-873`](../lib/api-client.ts:862)):
```typescript
static async updateAdminChannel(channelId: string, data: {
name?: string
commissionRate?: number
isActive?: boolean // 应该是 status?: "active" | "inactive"
}) {
```
#### 4.3 更新Agent资源配置 - 🔴 参数名不匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `PUT /api/admin/resources/agents/{agent_id}/config` | `PUT /api/admin/resources/agents/${agentId}/config` | ✅ |
| 参数 cpu | float, 可选 | ❌ 未定义 | 🔴 |
| 参数 memory | float, 可选 | ❌ 未定义 | 🔴 |
| 参数 maxInstances | int, 可选 | ❌ 未定义 | 🔴 |
| 参数 name | ❌ 未定义 | string, 可选 | ⚠️ |
| 参数 description | ❌ 未定义 | string, 可选 | ⚠️ |
| 参数 price | ❌ 未定义 | number, 可选 | ⚠️ |
| 参数 category | ❌ 未定义 | string, 可选 | ⚠️ |
| 参数 frameworkTemplate | ❌ 未定义 | string, 可选 | ⚠️ |
| 参数 isActive | ❌ 未定义 | boolean, 可选 | ⚠️ |
**问题**: 前端和后端的参数完全不匹配!
**后端文档**:
```json
{
"cpu": 4.0,
"memory": 8.0,
"maxInstances": 10
}
```
**前端代码** ([`api-client.ts:1028-1042`](../lib/api-client.ts:1028)):
```typescript
static async updateAgentResourceConfig(agentId: string, data: {
name?: string
description?: string
price?: number
category?: string
frameworkTemplate?: string
isActive?: boolean
}) {
```
**建议**: 修改前端参数定义以匹配后端:
```typescript
static async updateAgentResourceConfig(agentId: string, data: {
cpu?: number
memory?: number
maxInstances?: number
}) {
```
#### 4.4 更新渠道供应商授权 - ⚠️ 参数传递方式不同
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `PUT /api/admin/providers/access/{access_id}` | `PUT /api/admin/providers/access/${accessId}` | ✅ |
| 参数传递方式 | Query Parameters | Query Parameters | ✅ |
| 参数 status | query param | query param | ✅ |
| 参数 rpm_limit | query param (snake_case) | query param (rpmLimit → rpm_limit) | ✅ |
| 参数 tpm_limit | query param (snake_case) | query param (tpmLimit → tpm_limit) | ✅ |
**前端代码** ([`api-client.ts:914-932`](../lib/api-client.ts:914)):
```typescript
static async updateChannelProviderAccess(accessId: string, params: {
status?: "active" | "suspended" | "expired"
rpmLimit?: number
tpmLimit?: number
}) {
const queryParams = new URLSearchParams()
if (params.status) queryParams.append("status", params.status)
if (params.rpmLimit) queryParams.append("rpm_limit", params.rpmLimit.toString())
if (params.tpmLimit) queryParams.append("tpm_limit", params.tpmLimit.toString())
// ...
}
```
**分析**: 前端正确地将 camelCase 转换为 snake_case,匹配后端期望的参数名。
---
### 5. 监控相关 (`/api/v1/monitoring`)
#### 5.1 获取系统性能指标 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `GET /api/v1/monitoring/metrics` | `GET /api/v1/monitoring/metrics` | ✅ |
#### 5.2 获取服务统计信息 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `GET /api/v1/monitoring/stats` | `GET /api/v1/monitoring/stats` | ✅ |
| 参数 service | query param | query param | ✅ |
#### 5.3 获取性能趋势数据 - ✅ 匹配
| 项目 | 后端文档 | 前端实现 | 状态 |
|------|---------|---------|------|
| 路径 | `GET /api/v1/monitoring/trends` | `GET /api/v1/monitoring/trends` | ✅ |
| 参数 metric | query param | query param | ✅ |
| 参数 period | query param | query param | ✅ |
| 参数 interval | query param | query param | ✅ |
---
### 6. 前端页面硬编码数据问题
#### 6.1 渠道仪表板 - 硬编码数据
**文件**: [`app/channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx)
**问题**: 页面中存在大量硬编码的模拟数据,而不是从API获取。
**硬编码示例** (第702-724行):
```typescript
const platformModelProviders = [
{ id: 1, name: "OpenAI", status: "active", requests: 52000, latency: 150, uptime: "99.9%", icon: "🤖" },
{ id: 2, name: "Anthropic", status: "active", requests: 38000, latency: 180, uptime: "99.8%", icon: "🧠" },
{ id: 3, name: "Google AI", status: "active", requests: 25000, latency: 120, uptime: "99.95%", icon: "🔍" },
{ id: 4, name: "Meta Llama", status: "active", requests: 15000, latency: 95, uptime: "99.7%", icon: "🦙" },
]
const platformDataProviders = [
{ id: 1, name: "RapidAPI", status: "active", apis: 8000, calls: 2200000, capacity: "95%", icon: "⚡" },
{ id: 2, name: "API Hub", status: "active", apis: 5000, calls: 1500000, capacity: "87%", icon: "🔗" },
{ id: 3, name: "OpenData", status: "active", apis: 3000, calls: 800000, capacity: "92%", icon: "📊" },
]
```
**影响**: 这些数据不会随后端实际数据变化而更新,导致页面显示的信息与实际不符。
#### 6.2 概览页面Agent数据 - 硬编码
**文件**: [`app/channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx) (第839-869行)
```typescript
{[
{ name: "Weather Query Agent", nameZh: "天气查询代理", allocated: 10, icon: "☁️" },
{ name: "Data Analysis Agent", nameZh: "数据分析代理", allocated: 15, icon: "📊" },
{ name: "Document Processing Agent", nameZh: "文档处理代理", allocated: 8, icon: "📄" },
// ...
].map((agent) => (
// ...
))}
```
**建议**: 应该使用 `agentResourcesData` 状态变量中的数据,该数据已通过 `TaijiAPIClient.getAdminAgentResources()` 获取。
---
## 📊 响应数据结构对比
### 1. 获取租户列表响应
**后端文档**:
```json
{
"success": true,
"data": {
"tenants": [
{
"id": "tenant-uuid-1",
"name": "企业客户A",
"email": "contact@company-a.com",
"subscriptionTier": "pro",
"balance": 1500.00,
"creditLimit": 2000.00,
"status": "active",
"createdAt": "2025-12-01T00:00:00Z"
}
]
}
}
```
**前端期望** (从 [`channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx) 分析):
```typescript
// 前端使用的字段
tenant.id
tenant.name
tenant.status
tenant.plan // ⚠️ 后端是 subscriptionTier
tenant.users // ⚠️ 后端未返回此字段
tenant.revenue // ⚠️ 后端未返回此字段
```
**问题**: 前端期望 `plan`, `users`, `revenue` 字段,但后端返回的是 `subscriptionTier`, 且没有 `users` 和 `revenue` 字段。
### 2. 获取Agent资源响应
**后端文档**:
```json
{
"success": true,
"data": {
"agents": [
{
"id": "agent-uuid-1",
"name": "weather-agent",
"type": "platform",
"category": "数据查询",
"cpu": 2.0,
"memory": 4.0,
"status": "active"
}
]
}
}
```
**前端期望** (从 [`channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx:1084-1158) 分析):
```typescript
// 前端使用的字段
agent.id
agent.name
agent.description // ⚠️ 后端未返回
agent.status
agent.cpu
agent.memory
agent.quantity // ⚠️ 后端未返回,前端使用 agent.quantity ?? agent.available ?? 0
agent.usage?.cpu // ⚠️ 后端未返回
agent.usage?.memory // ⚠️ 后端未返回
```
**问题**: 前端期望 `description`, `quantity`, `usage` 等字段,但后端未返回这些字段。
### 3. 获取模型供应商响应
**后端文档**:
```json
{
"success": true,
"data": {
"providers": [
{
"id": "provider-uuid-1",
"name": "OpenAI",
"provider": "openai",
"apiUrl": "https://api.openai.com/v1",
"supportedModels": ["gpt-4", "gpt-4o-mini"],
"rpm": 3500,
"tpm": 90000,
"status": "active",
"isActive": true
}
]
}
}
```
**前端期望** (从 [`channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx:1169-1256) 分析):
```typescript
// 前端使用的字段
provider.id
provider.name
provider.provider || provider.type // 后端返回 provider
provider.status || provider.isActive
provider.supportedModels
provider.rpm
provider.tpm
provider.hasAccess // ⚠️ 仅渠道API返回
provider.pendingApplication // ⚠️ 仅渠道API返回
```
**分析**: 前端同时支持管理员API和渠道API的响应格式,但需要注意 `hasAccess` 和 `pendingApplication` 字段仅在渠道API (`/api/channel/providers`) 中返回。
---
## 🔧 修复建议
### 高优先级修复
#### 1. 修复 `createAdmin` 缺少 `channelId` 参数
**文件**: [`lib/api-client.ts`](../lib/api-client.ts:807)
```typescript
// 修改前
static async createAdmin(data: {
name: string
email: string
password: string
role: "billing_admin" | "operations_admin"
}) {
// 修改后
static async createAdmin(data: {
name: string
email: string
password: string
role: "billing_admin" | "operations_admin"
channelId: string // 添加必需参数
}) {
```
#### 2. 修复 `updateAgentResourceConfig` 参数不匹配
**文件**: [`lib/api-client.ts`](../lib/api-client.ts:1028)
```typescript
// 修改前
static async updateAgentResourceConfig(agentId: string, data: {
name?: string
description?: string
price?: number
category?: string
frameworkTemplate?: string
isActive?: boolean
}) {
// 修改后
static async updateAgentResourceConfig(agentId: string, data: {
cpu?: number
memory?: number
maxInstances?: number
}) {
```
#### 3. 移除不存在的 `disableTenant` 和 `enableTenant` 接口
**文件**: [`lib/api-client.ts`](../lib/api-client.ts:629-646)
建议删除这两个方法,改用 `updateTenantStatus`:
```typescript
// 删除 disableTenant 和 enableTenant 方法
// 使用 updateTenantStatus 代替
static async updateTenantStatus(tenantId: string, status: "active" | "inactive" | "suspended") {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/status`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify({ status }),
})
return handleResponse(response)
}
```
#### 4. 修复 `updateAdminChannel` 参数
**文件**: [`lib/api-client.ts`](../lib/api-client.ts:862)
```typescript
// 修改前
static async updateAdminChannel(channelId: string, data: {
name?: string
commissionRate?: number
isActive?: boolean
}) {
// 修改后
static async updateAdminChannel(channelId: string, data: {
name?: string
email?: string
commissionRate?: number
status?: "active" | "inactive"
}) {
```
### 中优先级修复
#### 5. 统一 gateway 参数值
前端多处使用 `"MCP" | "A2A" | "API"`,但后端文档显示应为 `"MCP" | "LiteLLM"`。需要与后端确认正确的值。
#### 6. 移除硬编码数据
在 [`app/channel/dashboard/page.tsx`](../app/channel/dashboard/page.tsx) 中,将硬编码的 `platformModelProviders` 和 `platformDataProviders` 替换为从API获取的数据。
---
## 📈 监控配置数据为空的原因分析
根据用户反馈"监控配置的信息都没有内容",分析可能的原因:
### 1. 后端返回模拟数据
后端API文档中的响应示例都是模拟数据,实际后端可能:
- 返回空数组 `[]`
- 返回默认值 `0`
- 数据库中没有实际业务数据
### 2. 前端使用硬编码数据
如上文分析,前端多处使用硬编码数据而非API返回的数据,导致:
- 即使后端有数据,前端也不会显示
- 页面显示的是静态模拟数据
### 3. API调用失败但静默处理
前端代码中存在多处 `try-catch` 静默处理错误:
```typescript
// channel/dashboard/page.tsx:313-330
try {
const providersResponse = await TaijiAPIClient.getChannelProviders()
if (providersResponse.success && providersResponse.data?.providers) {
setModelProvidersData(providersResponse.data.providers)
}
} catch (providerError) {
console.warn("Failed to load channel providers:", providerError)
// 静默失败,不显示错误给用户
}
```
### 4. 权限问题
某些API需要特定角色权限:
- 渠道管理员无法访问 `/api/admin/resources/agents`
- 普通用户无法访问 `/api/channel/tenants`
---
## 🎯 总结
### 问题统计
| 类别 | 问题数量 | 影响程度 |
|------|---------|---------|
| 参数名称不匹配 | 3 | 🔴 高 - 导致API调用失败 |
| 响应数据结构不一致 | 5 | 🔴 高 - 导致数据无法正确显示 |
| 前端缺少必需参数 | 2 | 🟡 中 - 特定功能无法使用 |
| 前端使用硬编码数据 | 4 | 🟡 中 - 数据不真实 |
| 接口不存在 | 2 | 🔴 高 - 功能完全无法使用 |
### 建议优先级
1. **立即修复**: `createAdmin` 缺少 `channelId`、`updateAgentResourceConfig` 参数不匹配
2. **尽快修复**: 移除 `disableTenant`/`enableTenant`,使用 `updateTenantStatus`
3. **计划修复**: 移除硬编码数据,使用API返回的真实数据
4. **需要确认**: gateway 参数值 (`MCP/A2A/API` vs `MCP/LiteLLM`)
### 下一步行动
1. 与后端开发确认API文档是否为最新版本
2. 修复前端API客户端中的参数问题
3. 移除硬编码数据,确保使用API返回的真实数据
4. 添加更好的错误处理和用户提示
5. 测试所有API接口的实际响应
---
**报告生成者**: Claude AI
**审核状态**: 待审核
-732
View File
@@ -1,732 +0,0 @@
# Taiji AI Platform 前端代码优化建议
## 📌 概述
本文档基于对整个前端项目的代码审查,提出了架构优化、代码质量改进和最佳实践建议。
---
## 🔴 高优先级问题
### 1. API 客户端逻辑错误
**问题位置**: `lib/api-client.ts`(第1000+行)
**具体问题**:
```typescript
// ❌ 错误的删除Agent接口
static async deleteTool(toolId: string) {
const response = await fetch(
`${API_BASE_URLS.dataIngestion}/api/tools/delete?id=${toolId}`,
{ method: "DELETE", headers: buildHeaders() }
)
return handleResponse(response)
}
```
**为什么这是错的**:
1. 调用的是 Data Ingestion 服务的删除工具接口,不是 MCP Server 的删除 Agent 接口
2. 在前端 Agent 管理页面中被错误使用
3. 参数格式不符合 RESTful 最佳实践(应该在路径中,不是查询字符串)
**修复方案**:
```typescript
/**
* 删除Agent资源(超级管理员)
*/
static async deleteAdminAgent(agentId: string) {
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/admin/resources/agents/${agentId}`,
{
method: "DELETE",
headers: buildHeaders(),
}
)
return handleResponse(response)
}
/**
* 删除用户自定义Agent
*/
static async deleteUserAgent(agentId: string) {
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/user/agents/${agentId}`,
{
method: "DELETE",
headers: buildHeaders(),
}
)
return handleResponse(response)
}
/**
* 删除工具(Data Ingestion 服务)
*/
static async deleteTool(toolId: string) {
const response = await fetch(
`${API_BASE_URLS.dataIngestion}/api/tools/${toolId}`,
{
method: "DELETE",
headers: buildHeaders(),
}
)
return handleResponse(response)
}
```
**影响的文件**:
- `app/admin/dashboard/page.tsx` - ResourcesTab 组件
- `app/agent-factory/page.tsx` - Agent 删除功能
---
### 2. 缺失的 API 实现
**问题**: 前端代码调用了后端没有实现的 API
#### 2.1 删除渠道接口
**前端代码**:
```typescript
// app/admin/dashboard/page.tsx
const handleDeleteChannel = async (channelId: string) => {
// 当前没有实现,但UI中有删除按钮
}
```
**需要实现**: `DELETE /api/admin/channels/{channelId}`
**后端建议**:
```python
@router.delete("/channels/{channel_id}", tags=["admin"])
async def delete_channel(
channel_id: str,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)
):
"""删除渠道(软删除)"""
# 1. 验证超级管理员权限
# 2. 检查是否有活跃租户
# 3. 软删除渠道(更新status字段)
# 4. 返回成功响应
```
#### 2.2 更新渠道接口
**前端代码**:
```typescript
// app/admin/dashboard/page.tsx
const handleUpdateChannel = async (channelId: string, data: any) => {
// 当前没有实现
}
```
**需要实现**: `PUT /api/admin/channels/{channelId}`
#### 2.3 工作流相关接口
**缺失接口**:
- `GET /api/user/workflows` - 获取用户工作流列表
- `GET /api/user/workflows/{workflowId}` - 获取工作流详情
- `PUT /api/user/workflows/{workflowId}` - 更新工作流
- `DELETE /api/user/workflows/{workflowId}` - 删除工作流
- `POST /api/user/workflows/{workflowId}/execute` - 执行工作流
---
## 🟡 中优先级问题
### 3. API 客户端架构问题
**问题**: `lib/api-client.ts` 已有 1443 行,单一责任原则违反
**当前状况**:
```
api-client.ts: 1443 行
├── 认证相关: ~200 行
├── 用户接口: ~400 行
├── 渠道接口: ~300 行
├── 管理员接口: ~300 行
└── 工具函数: ~100 行
```
**建议方案** - 分离为多个模块:
```
lib/
├── api-client.ts (基础工具和导出)
├── api/
│ ├── auth.ts (认证相关)
│ ├── user.ts (用户接口)
│ ├── channel.ts (渠道接口)
│ ├── admin.ts (管理员接口)
│ ├── tools.ts (工具相关)
│ └── providers.ts (供应商相关)
└── types/
├── auth.ts
├── agent.ts
├── billing.ts
└── common.ts
```
**代码示例**:
```typescript
// lib/api/auth.ts
import { APIResponse, buildHeaders, handleResponse, API_BASE_URLS } from '../api-client'
export class AuthAPI {
static async login(
email: string,
password: string,
role: 'user' | 'channel' | 'admin' | 'provider' = 'user'
): Promise<APIResponse<{ token: string; refreshToken?: string; user?: any }>> {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, role }),
})
return handleResponse(response)
}
static async logout() {
// ...
}
}
// lib/api-client.ts (重构后)
export { AuthAPI } from './api/auth'
export { UserAPI } from './api/user'
export { ChannelAPI } from './api/channel'
export { AdminAPI } from './api/admin'
```
**使用方式**:
```typescript
import { AuthAPI, UserAPI, AdminAPI } from '@/lib/api-client'
// 登录
const result = await AuthAPI.login(email, password)
// 部署Agent
const deployment = await UserAPI.deployAgent(agentId, instances, model)
// 获取平台统计
const stats = await AdminAPI.getDashboardStats()
```
---
### 4. 全局状态管理缺失
**问题**:
```typescript
// ❌ 反面例子 - 多个地方重复调用
const [agents, setAgents] = useState<any[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
const loadAgents = async () => {
try {
const result = await TaijiAPIClient.getPlatformAgents()
setAgents(result?.data?.data || [])
} catch (error) {
console.error("Failed to load agents:", error)
}
}
loadAgents()
}, [])
```
这个模式在 `agent-factory.tsx`, `orchestration.tsx`, `billing.tsx` 等多个文件中重复出现。
**建议方案** - 使用 Zustand 创建全局状态:
```typescript
// lib/store/agent-store.ts
import { create } from 'zustand'
import { UserAPI } from '@/lib/api-client'
interface AgentState {
agents: any[]
loading: boolean
error: string | null
// Actions
fetchAgents: () => Promise<void>
deployAgent: (agentId: string, instances: number, model: string) => Promise<void>
getAgentById: (id: string) => any | null
}
export const useAgentStore = create<AgentState>((set, get) => ({
agents: [],
loading: false,
error: null,
fetchAgents: async () => {
set({ loading: true, error: null })
try {
const result = await UserAPI.getPlatformAgents()
set({ agents: result?.data?.data || [] })
} catch (error) {
set({ error: error?.message || 'Failed to fetch agents' })
} finally {
set({ loading: false })
}
},
deployAgent: async (agentId: string, instances: number, model: string) => {
try {
const result = await UserAPI.deployAgent({
agentId,
instances,
model,
gateway: 'MCP'
})
// 部署后刷新列表
await get().fetchAgents()
} catch (error) {
set({ error: error?.message })
}
},
getAgentById: (id: string) => {
return get().agents.find(a => a.id === id)
}
}))
```
**使用方式**:
```typescript
// app/agent-factory/page.tsx
import { useAgentStore } from '@/lib/store/agent-store'
export default function AgentFactoryPage() {
const { agents, loading, fetchAgents, deployAgent } = useAgentStore()
useEffect(() => {
fetchAgents()
}, [fetchAgents])
return (
<div>
{loading ? <Spinner /> : agents.map(agent => (...))}
</div>
)
}
```
---
### 5. 错误处理不统一
**问题**:
```typescript
// ❌ 多种错误处理方式混乱
try {
const result = await TaijiAPIClient.login(...)
if (result?.success && result.data?.token) {
// 处理成功
}
} catch (error) {
// 处理异常
console.error("Failed to login:", error)
toast({ ... })
}
```
**建议方案** - 创建统一的错误处理器:
```typescript
// lib/error-handler.ts
export class APIError extends Error {
constructor(
public code: string,
public message: string,
public statusCode: number = 500,
public details?: any
) {
super(message)
}
}
export function handleAPIError(error: any): APIError {
// 如果是已知的APIError,直接返回
if (error instanceof APIError) {
return error
}
// 如果是响应错误
if (error.response) {
const { status, data } = error.response
return new APIError(
data?.error?.code || 'UNKNOWN_ERROR',
data?.error?.message || data?.detail || 'An error occurred',
status,
data?.error?.details
)
}
// 网络错误
if (error.message?.includes('Failed to fetch')) {
return new APIError(
'NETWORK_ERROR',
'Unable to connect to the server. Please check your connection.',
0
)
}
// 其他错误
return new APIError(
'UNKNOWN_ERROR',
error.message || 'An unexpected error occurred',
500
)
}
// 使用
try {
const result = await AuthAPI.login(email, password)
if (result.success) {
// ...
}
} catch (error) {
const apiError = handleAPIError(error)
toast({
title: "错误",
description: apiError.message,
variant: "destructive"
})
logger.error('Login failed', { error: apiError })
}
```
---
### 6. Token 刷新机制不完善
**问题**:
```typescript
// ❌ 当Token过期时,用户必须重新登录
if (response.status === 401) {
// 清除token并重定向到登录
localStorage.removeItem("auth_token")
router.push("/login")
}
```
**建议方案** - 实现自动 Token 刷新:
```typescript
// lib/api-client.ts
async function handleResponse<T = any>(response: Response): Promise<T> {
// Token过期 (401) 时自动刷新
if (response.status === 401) {
try {
const refreshResult = await refreshToken()
if (refreshResult.success && refreshResult.data?.token) {
// 重试原请求
const retryResponse = await fetch(response.url, {
...response,
headers: {
...response.headers,
Authorization: `Bearer ${refreshResult.data.token}`
}
})
return handleResponse<T>(retryResponse)
}
} catch (error) {
// 刷新失败,重定向到登录
clearAuth()
window.location.href = '/login'
}
}
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: response.statusText }))
throw new APIError(
(error as any).error?.code || 'UNKNOWN',
(error as any).detail || `HTTP error! status: ${response.status}`,
response.status
)
}
return response.json() as Promise<T>
}
```
---
## 🟢 低优先级建议
### 7. 代码质量改进
#### 7.1 添加类型定义
```typescript
// 📂 lib/types/index.ts
export interface User {
id: string
email: string
name: string
role: UserRole
subscription_tier: SubscriptionTier
balance: number
status: 'active' | 'inactive' | 'suspended'
}
export interface Agent {
id: string
name: string
type: 'platform' | 'custom'
description: string
category: string
status: 'available' | 'unavailable' | 'error'
capabilities: string[]
required_resources: {
cpu: number
memory: number
}
}
export type UserRole = 'user' | 'channel' | 'admin' | 'super_admin' | 'provider'
export type SubscriptionTier = 'free' | 'pro' | 'enterprise'
```
#### 7.2 环境变量管理
```typescript
// 📂 lib/env.ts
const requiredEnvVars = [
'NEXT_PUBLIC_MCP_SERVER_URL',
'NEXT_PUBLIC_DATA_INGESTION_URL',
'NEXT_PUBLIC_API_GATEWAY_URL'
]
for (const envVar of requiredEnvVars) {
if (!process.env[envVar]) {
throw new Error(`Missing required environment variable: ${envVar}`)
}
}
export const env = {
MCP_SERVER_URL: process.env.NEXT_PUBLIC_MCP_SERVER_URL!,
DATA_INGESTION_URL: process.env.NEXT_PUBLIC_DATA_INGESTION_URL!,
API_GATEWAY_URL: process.env.NEXT_PUBLIC_API_GATEWAY_URL!,
}
```
#### 7.3 请求拦截器
```typescript
// 📂 lib/api-interceptor.ts
export class RequestInterceptor {
private static instance: RequestInterceptor
static getInstance() {
if (!this.instance) {
this.instance = new RequestInterceptor()
}
return this.instance
}
async intercept(url: string, options: RequestInit) {
// 1. 添加认证header
const token = getAuthToken()
if (token) {
options.headers = {
...options.headers,
'Authorization': `Bearer ${token}`
}
}
// 2. 添加请求ID用于追踪
const requestId = crypto.randomUUID()
options.headers = {
...options.headers,
'X-Request-ID': requestId
}
// 3. 记录请求
console.log(`[${requestId}] ${options.method} ${url}`)
return { url, options }
}
}
```
#### 7.4 日志系统
```typescript
// 📂 lib/logger.ts
export class Logger {
static info(message: string, data?: any) {
console.log(`[INFO] ${new Date().toISOString()} - ${message}`, data)
}
static error(message: string, error?: any) {
console.error(`[ERROR] ${new Date().toISOString()} - ${message}`, error)
}
static warn(message: string, data?: any) {
console.warn(`[WARN] ${new Date().toISOString()} - ${message}`, data)
}
static debug(message: string, data?: any) {
if (process.env.NODE_ENV === 'development') {
console.debug(`[DEBUG] ${new Date().toISOString()} - ${message}`, data)
}
}
}
```
---
### 8. 性能优化建议
#### 8.1 实现缓存策略
```typescript
// 📂 lib/cache.ts
export class CacheManager {
private static cache = new Map<string, { data: any; expiry: number }>()
static set(key: string, data: any, ttl: number = 5 * 60 * 1000) {
this.cache.set(key, {
data,
expiry: Date.now() + ttl
})
}
static get(key: string) {
const item = this.cache.get(key)
if (!item) return null
if (Date.now() > item.expiry) {
this.cache.delete(key)
return null
}
return item.data
}
static clear(key?: string) {
if (key) {
this.cache.delete(key)
} else {
this.cache.clear()
}
}
}
// 使用
const getPlatformAgents = async () => {
const cacheKey = 'platform_agents'
// 先查缓存
const cached = CacheManager.get(cacheKey)
if (cached) return cached
// 缓存未命中,调用API
const result = await UserAPI.getPlatformAgents()
// 缓存结果(5分钟)
if (result.success) {
CacheManager.set(cacheKey, result.data, 5 * 60 * 1000)
}
return result.data
}
```
#### 8.2 代码分割优化
```typescript
// 📂 app/admin/layout.tsx
const AdminDashboard = dynamic(
() => import('./dashboard/page'),
{ loading: () => <Spinner /> }
)
```
---
### 9. 测试建议
#### 9.1 单元测试
```typescript
// 📂 lib/__tests__/api-client.test.ts
import { AuthAPI } from '@/lib/api-client'
describe('AuthAPI', () => {
it('should login successfully with correct credentials', async () => {
const result = await AuthAPI.login('test@example.com', 'password')
expect(result.success).toBe(true)
expect(result.data?.token).toBeDefined()
})
it('should fail login with incorrect credentials', async () => {
expect(async () => {
await AuthAPI.login('test@example.com', 'wrongpassword')
}).rejects.toThrow()
})
})
```
#### 9.2 集成测试
```typescript
// 📂 __tests__/integration/agent-deployment.test.ts
describe('Agent Deployment Flow', () => {
it('should complete full agent deployment flow', async () => {
// 1. 登录
const loginResult = await AuthAPI.login(...)
// 2. 获取Agent列表
const agents = await UserAPI.getPlatformAgents()
// 3. 部署Agent
const deployment = await UserAPI.deployAgent(...)
// 4. 验证部署成功
expect(deployment.success).toBe(true)
})
})
```
---
## 📋 优化实施计划
### Phase 1 (第1周) - 高优先级修复
- [ ] 分离 `api-client.ts` 为多个模块
- [ ] 修复 Agent 删除接口逻辑
- [ ] 实现缺失的 API(删除/更新渠道)
- [ ] 添加 Token 自动刷新机制
### Phase 2 (第2周) - 中优先级改进
- [ ] 实现全局状态管理(Zustand)
- [ ] 添加统一的错误处理
- [ ] 添加日志系统
- [ ] 优化 API 调用(缓存、去重)
### Phase 3 (第3周) - 代码质量
- [ ] 添加完整的类型定义
- [ ] 实现请求拦截器
- [ ] 添加单元测试
- [ ] 性能优化(代码分割、缓存)
### Phase 4 (第4周) - 测试和文档
- [ ] 集成测试
- [ ] 性能测试
- [ ] 更新API文档
- [ ] 编写开发指南
---
## 总结
通过上述优化,可以显著提升项目的:
- ✅ **可维护性**: 清晰的架构和分离的关注点
- ✅ **可扩展性**: 模块化设计便于添加新功能
- ✅ **性能**: 缓存、请求优化、代码分割
- ✅ **可靠性**: 统一的错误处理和日志记录
- ✅ **开发效率**: 减少重复代码,提高代码复用率
**预期工作量**: 2-3周
**优先级排序**: 高→中→低
-161
View File
@@ -1,161 +0,0 @@
# 缺失的 API 接口清单
根据前端代码和 API 文档的对比,以下接口在 API 文档中**没有提供**:
## 1. 删除 Agent 接口
**前端使用位置**: `/app/admin/dashboard/page.tsx` (资源管理标签页)
**当前实现**:
- 前端使用 `TaijiAPIClient.deleteTool(agent.id || agent.name)` 来删除 Agent
- 这个接口实际上是删除 Data Ingestion 服务中的工具,而不是删除 Agent 资源
**需要的接口**:
```
DELETE /api/admin/resources/agents/{agent_id}
```
**请求示例**:
```bash
curl -X DELETE "http://localhost:8002/api/admin/resources/agents/agent-uuid-1" \
-H "Authorization: Bearer <admin_token>"
```
**响应示例**:
```json
{
"success": true,
"message": "Agent资源已删除"
}
```
**说明**:
- 当前前端代码错误地使用了 `deleteTool` 接口来删除 Agent
- 应该提供一个专门的删除 Agent 资源的接口
- 删除应该是软删除,仅标记为不活跃
---
## 2. 删除渠道接口
**前端使用位置**: `/app/admin/dashboard/page.tsx` (渠道管理标签页)
**当前状态**:
- 前端UI中有"删除渠道"按钮,但没有实现对应的API调用
**需要的接口**:
```
DELETE /api/admin/channels/{channel_id}
```
**请求示例**:
```bash
curl -X DELETE "http://localhost:8002/api/admin/channels/channel-uuid-1" \
-H "Authorization: Bearer <admin_token>"
```
**响应示例**:
```json
{
"success": true,
"message": "渠道已删除"
}
```
**说明**:
- 删除渠道前应该检查是否有关联的租户
- 如果有租户,应该提示或阻止删除
- 删除应该是软删除,仅标记为不活跃
---
## 3. 更新渠道信息接口
**前端使用位置**: `/app/admin/dashboard/page.tsx` (渠道管理标签页)
**当前状态**:
- 前端可能有编辑渠道信息的功能,但需要确认是否有对应的API
**需要的接口**:
```
PUT /api/admin/channels/{channel_id}
```
**请求体**:
```json
{
"name": "合作渠道A(更新)",
"email": "new-email@channel-a.com",
"commissionRate": 12.0,
"status": "active"
}
```
**响应示例**:
```json
{
"success": true,
"data": {
"id": "channel-uuid-1",
"name": "合作渠道A(更新)",
"email": "new-email@channel-a.com"
},
"message": "渠道信息更新成功"
}
```
---
## 4. 更新 Agent 资源配置接口
**前端使用位置**: `/app/admin/dashboard/page.tsx` (资源管理标签页 - Agent资源配置对话框)
**当前状态**:
- 前端有配置 Agent CPU 和内存的对话框,但保存时没有调用API
**需要的接口**:
```
PUT /api/admin/resources/agents/{agent_id}/config
```
**请求体**:
```json
{
"cpu": 4.0,
"memory": 8.0,
"maxInstances": 10
}
```
**响应示例**:
```json
{
"success": true,
"message": "Agent资源配置更新成功"
}
```
---
## 总结
### 必须实现的接口(前端已使用):
1. ❌ **DELETE /api/admin/resources/agents/{agent_id}** - 删除Agent资源
- 当前前端错误地使用了 `deleteTool` 接口
### 建议实现的接口(前端UI已存在但未实现):
2. ❌ **DELETE /api/admin/channels/{channel_id}** - 删除渠道
3. ⚠️ **PUT /api/admin/channels/{channel_id}** - 更新渠道信息
4. ⚠️ **PUT /api/admin/resources/agents/{agent_id}/config** - 更新Agent资源配置
### 已实现的接口(前端已使用):
✅ 所有其他接口都已实现并在API文档中有说明
---
## 修复建议
1. **立即修复**: 实现 `DELETE /api/admin/resources/agents/{agent_id}` 接口,并更新前端代码使用正确的接口
2. **优先级高**: 实现 `DELETE /api/admin/channels/{channel_id}` 接口,完善渠道管理功能
3. **优先级中**: 实现渠道和Agent的更新接口,提升管理功能的完整性
File diff suppressed because it is too large Load Diff
+839
View File
@@ -0,0 +1,839 @@
# 太极平台前端功能与后端接口需求文档
## 文档概述
本文档详细描述了太极平台(Taiji-Pad)前端各页面的功能、监控指标、按钮操作,以及所需的后端接口。文档基于前端页面代码直接分析生成,不依赖已有的 api-client.ts 文件。
---
## 目录
1. [认证模块](#1-认证模块)
2. [超级管理员仪表板](#2-超级管理员仪表板)
3. [渠道仪表板](#3-渠道仪表板)
4. [Agent工厂](#4-agent工厂)
5. [数据工具](#5-数据工具)
6. [模型网关](#6-模型网关)
7. [编排中心](#7-编排中心)
8. [计费中心](#8-计费中心)
9. [接口汇总表](#9-接口汇总表)
---
## 1. 认证模块
### 1.1 用户登录页面 (`app/login/page.tsx`)
#### 功能描述
普通用户(租户)登录入口,支持邮箱密码登录。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 输入框 | 邮箱 | 用户邮箱地址 |
| 输入框 | 密码 | 用户密码 |
| 按钮 | 登录 | 提交登录请求 |
| 链接 | 忘记密码 | 跳转密码重置页面 |
| 链接 | 注册 | 跳转注册页面 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/auth/login` | POST | 用户登录 | `{ email, password, role: "user" }` | `{ success, data: { token, refreshToken, user } }` |
---
### 1.2 管理员登录页面 (`app/admin/login/page.tsx`)
#### 功能描述
超级管理员登录入口,支持邮箱密码登录。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 输入框 | 邮箱 | 管理员邮箱地址 |
| 输入框 | 密码 | 管理员密码 |
| 按钮 | 登录 | 提交登录请求 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/auth/login` | POST | 管理员登录 | `{ email, password, role: "super_admin" }` | `{ success, data: { token, refreshToken, user } }` |
---
### 1.3 渠道登录页面 (`app/channel/login/page.tsx`)
#### 功能描述
渠道合作伙伴登录入口,支持邮箱密码登录。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 输入框 | 邮箱 | 渠道管理员邮箱 |
| 输入框 | 密码 | 渠道管理员密码 |
| 按钮 | 登录 | 提交登录请求 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/auth/login` | POST | 渠道登录 | `{ email, password, role: "channel" }` | `{ success, data: { token, refreshToken, user } }` |
---
## 2. 超级管理员仪表板
### 文件位置
`app/admin/dashboard/page.tsx` (4417行)
### 2.1 概览标签页 (Overview)
#### 功能描述
展示平台整体运营数据和系统健康状态。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 总渠道数 | 平台注册的渠道总数 | `stats.total_channels` |
| 总租户数 | 平台所有租户总数 | `stats.total_tenants` |
| 活跃租户 | 当前活跃的租户数量 | `stats.active_tenants` |
| 总收入 | 平台总收入金额 | `stats.total_revenue` |
| CPU使用率 | 系统CPU使用百分比 | `stats.cpu_usage` |
| 内存使用率 | 系统内存使用百分比 | `stats.memory_usage` |
| 存储使用率 | 系统存储使用百分比 | `stats.storage_usage` |
| API请求/分钟 | 每分钟API请求数 | `stats.api_requests` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片 | 统计卡片 | 显示4个核心统计指标 |
| 进度条 | 系统指标 | 显示CPU/内存/存储/API使用率 |
| 列表 | 最近租户 | 显示最近注册的租户列表 |
| 搜索框 | 搜索租户 | 按名称搜索租户 |
| 警告卡片 | 系统警告 | 显示系统告警信息 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 查看详情 | 查看租户详细信息 | 无(本地状态) |
| 暂停 | 暂停租户账户 | 需要接口 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/dashboard/stats` | GET | 获取仪表板统计数据 | 无 | `{ total_channels, total_tenants, active_tenants, total_revenue, cpu_usage, memory_usage, storage_usage, api_requests }` |
| `/api/admin/tenants` | GET | 获取租户列表 | `{ page?, limit?, search? }` | `{ success, data: { tenants: [...] } }` |
---
### 2.2 渠道管理标签页 (Channels)
#### 功能描述
管理分销渠道及其租户组合。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 搜索框 | 搜索渠道 | 按名称搜索渠道 |
| 按钮 | 添加渠道 | 打开创建渠道对话框 |
| 卡片列表 | 渠道列表 | 显示所有渠道信息 |
| 表格 | 渠道申请审批 | 供应商申请列表 |
| 表格 | Agent申请审批 | Agent申请列表 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 添加渠道 | 创建新渠道 | `POST /api/admin/channels/create` |
| 查看详情 | 查看渠道详细信息 | `GET /api/admin/channels/{id}` |
| 编辑 | 编辑渠道信息 | `PUT /api/admin/channels/{id}` |
| 查看租户 | 查看渠道下的租户 | `GET /api/channel/tenants` |
| 修改佣金 | 修改渠道佣金比例 | `PUT /api/admin/channels/{id}/resources` |
| 管理授权 | 管理渠道供应商授权 | `GET /api/admin/channels/{id}/provider-access` |
| 资源管理 | 配置渠道资源 | `PUT /api/admin/channels/{id}/resources` |
| 删除渠道 | 删除渠道 | `DELETE /api/admin/channels/{id}` |
| 添加租户 | 为渠道添加租户 | `POST /api/channel/tenants/create` |
| 管理权限 | 管理租户权限 | `PUT /api/channel/tenants/{id}/permissions` |
| 修改密码 | 修改租户密码 | `PUT /api/channel/tenants/{id}/password` |
| 禁用租户 | 禁用租户账户 | `PUT /api/channel/tenants/{id}/status` |
| 删除租户 | 删除租户 | `DELETE /api/channel/tenants/{id}` |
| 审批(供应商) | 审批供应商申请 | `POST /api/admin/applications/{id}/review` |
| 审批(Agent) | 审批Agent申请 | `POST /api/admin/applications/{id}/review` |
| 撤销授权 | 撤销渠道供应商授权 | `DELETE /api/admin/channels/provider-access/{id}` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/channels` | GET | 获取渠道列表 | 无 | `{ success, data: { channels: [...] } }` |
| `/api/admin/channels/create` | POST | 创建渠道 | `{ name, email, password, commissionRate }` | `{ success, data: { channel } }` |
| `/api/admin/channels/{id}` | GET | 获取渠道详情 | 无 | `{ success, data: { channel } }` |
| `/api/admin/channels/{id}` | PUT | 更新渠道信息 | `{ name, email, contactName, phone }` | `{ success }` |
| `/api/admin/channels/{id}` | DELETE | 删除渠道 | 无 | `{ success }` |
| `/api/admin/channels/{id}/resources` | GET | 获取渠道资源配置 | 无 | `{ success, data: { models, agents, customAgentResources, channelCredit } }` |
| `/api/admin/channels/{id}/resources` | PUT | 更新渠道资源配置 | `{ models, agents, customAgentResources, channelCredit }` | `{ success }` |
| `/api/admin/channels/{id}/admins` | GET | 获取渠道管理员列表 | 无 | `{ success, data: { admins: [...] } }` |
| `/api/admin/channels/{id}/provider-access` | GET | 获取渠道供应商授权 | 无 | `{ success, data: { accessList: [...] } }` |
| `/api/admin/channels/provider-access/{id}` | DELETE | 撤销供应商授权 | 无 | `{ success }` |
| `/api/admin/applications` | GET | 获取申请列表 | 无 | `[{ id, type, channelName, ... }]` |
| `/api/admin/applications/{id}/review` | POST | 审批申请 | `{ approved: boolean, comment }` | `{ success }` |
| `/api/channel/tenants` | GET | 获取渠道租户列表 | 无 | `{ success, data: { tenants: [...] } }` |
| `/api/channel/tenants/create` | POST | 创建租户 | `{ name, email, password, subscriptionTier, channelId? }` | `{ success, data: { tenant } }` |
| `/api/channel/tenants/{id}/permissions` | PUT | 更新租户权限 | `{ permissions: [...] }` | `{ success }` |
| `/api/channel/tenants/{id}/password` | PUT | 修改租户密码 | `{ newPassword }` | `{ success }` |
| `/api/channel/tenants/{id}/status` | PUT | 更新租户状态 | `{ status: "active" | "suspended" }` | `{ success }` |
| `/api/channel/tenants/{id}` | DELETE | 删除租户 | 无 | `{ success }` |
| `/api/admin/admins/create` | POST | 创建管理员 | `{ name, email, password, role, channelId? }` | `{ success, data: { admin } }` |
---
### 2.3 资源管理标签页 (Resources)
#### 功能描述
管理平台的Agent计算资源和模型供应商。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| Agent CPU使用率 | 各Agent的CPU使用百分比 | `agent.usage.cpu` |
| Agent 内存使用率 | 各Agent的内存使用百分比 | `agent.usage.memory` |
| Agent 状态 | Agent运行状态(活跃/空闲) | `agent.status` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片网格 | Agent资源卡片 | 显示各Agent的资源配置和使用情况 |
| 卡片网格 | 模型供应商卡片 | 显示各模型供应商信息 |
| 按钮 | 添加模型供应商 | 打开添加供应商对话框 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 配置(Agent) | 配置Agent资源 | 本地对话框 |
| 删除(Agent) | 删除Agent资源 | `DELETE /api/admin/agents/{id}` |
| 添加模型供应商 | 添加新供应商 | `POST /api/admin/providers/create` |
| 配置(供应商) | 配置供应商参数 | `PUT /api/admin/providers/{id}` |
| 测试延迟 | 测试供应商连接 | `POST /api/admin/providers/{id}/test` |
| 删除(供应商) | 删除供应商 | `DELETE /api/admin/providers/{id}` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/agents` | GET | 获取Agent资源列表 | 无 | `{ success, data: { agents: [...] } }` |
| `/api/admin/agents/{id}` | PUT | 更新Agent资源配置 | `{ cpu, memory, instances }` | `{ success }` |
| `/api/admin/agents/{id}` | DELETE | 删除Agent资源 | 无 | `{ success }` |
| `/api/admin/providers` | GET | 获取模型供应商列表 | 无 | `{ success, data: { providers: [...] } }` |
| `/api/admin/providers/create` | POST | 创建模型供应商 | `{ name, provider, apiUrl, apiKey, supportedModels, rpm, tpm }` | `{ success, data: { provider } }` |
| `/api/admin/providers/{id}` | PUT | 更新供应商配置 | `{ name, apiUrl, apiKey, supportedModels, rpm, tpm }` | `{ success }` |
| `/api/admin/providers/{id}` | DELETE | 删除供应商 | 无 | `{ success }` |
| `/api/admin/providers/{id}/test` | POST | 测试供应商连接 | 无 | `{ success, latency }` |
---
### 2.4 监控标签页 (Monitoring)
#### 功能描述
监控所有平台Agent的性能和健康状态。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| Agent状态 | 健康/警告/严重 | `agent.status` |
| CPU使用率 | Agent CPU使用百分比 | `agent.cpuUsage` |
| 内存使用率 | Agent内存使用百分比 | `agent.memoryUsage` |
| 响应时间 | 平均响应时间(ms) | `agent.responseTime` |
| 请求数量 | 总请求数 | `agent.requestCount` |
| 错误率 | 错误请求百分比 | `agent.errorRate` |
| 运行时间 | Agent运行时长 | `agent.uptime` |
| 最后活跃 | 最后活跃时间 | `agent.lastActive` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片网格 | Agent健康卡片 | 显示各Agent的健康状态和性能指标 |
| 进度条 | CPU使用率 | 可视化CPU使用情况 |
| 进度条 | 内存使用率 | 可视化内存使用情况 |
| 徽章 | 状态标签 | 显示健康/警告/严重状态 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/monitoring/agents` | GET | 获取Agent监控数据 | 无 | `{ success, data: { agents: [{ id, name, status, cpuUsage, memoryUsage, responseTime, requestCount, errorRate, uptime, lastActive }] } }` |
---
### 2.5 计费标签页 (Billing)
#### 功能描述
管理平台计费,支持渠道维度、租户维度和调用记录查看。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 渠道总数 | 有计费记录的渠道数 | `billingData.channelStats.length` |
| 总计费额 | 所有渠道总计费金额 | 计算值 |
| 总EU消耗 | 所有渠道EU消耗总量 | 计算值 |
| 租户总数 | 有计费记录的租户数 | `billingData.tenantStats.length` |
| 用户总价 | 所有租户总消费 | 计算值 |
| 平均消费 | 租户平均消费金额 | 计算值 |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 标签切换 | 维度切换 | 渠道维度/租户维度/调用记录 |
| 统计卡片 | 汇总数据 | 显示各维度汇总统计 |
| 表格 | 计费详情 | 显示详细计费记录 |
| 按钮 | 时间查询 | 打开时间范围选择对话框 |
| 按钮 | 筛选 | 打开筛选条件对话框 |
| 按钮 | 导出 | 导出计费数据 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 时间查询 | 按时间范围查询 | `GET /api/admin/billing/overview?startTime=&endTime=` |
| 筛选 | 按条件筛选 | 本地筛选 |
| 导出 | 导出计费数据 | `GET /api/admin/billing/overview?export=excel` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/billing/overview` | GET | 获取计费概览 | `{ startTime?, endTime?, export? }` | `{ success, data: { channelStats: [...], tenantStats: [...], callRecords: [...] } }` |
| `/api/admin/billing/channels` | GET | 获取渠道计费详情 | `{ startTime?, endTime? }` | `{ success, data: { channels: [...] } }` |
| `/api/admin/billing/tenants` | GET | 获取租户计费详情 | `{ startTime?, endTime? }` | `{ success, data: { tenants: [...] } }` |
| `/api/admin/billing/calls` | GET | 获取调用记录 | `{ startTime?, endTime?, page?, limit? }` | `{ success, data: { calls: [...], total } }` |
---
### 2.6 设置标签页 (Settings)
#### 功能描述
管理管理员账户和角色权限配置。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 组件 | SettingsTab | 管理员列表管理组件 |
| 卡片 | 角色卡片 | 计费管理员/运营管理员/超级管理员 |
| 复选框网格 | 权限配置 | 配置各角色可访问的标签页 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 添加管理员 | 创建新管理员 | `POST /api/admin/admins/create` |
| 删除管理员 | 删除管理员 | `DELETE /api/admin/admins/{id}` |
| 保存权限配置 | 保存角色权限 | `PUT /api/admin/roles/{role}/permissions` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/admin/admins` | GET | 获取管理员列表 | 无 | `{ success, data: { admins: [...] } }` |
| `/api/admin/admins/create` | POST | 创建管理员 | `{ name, email, password, role }` | `{ success, data: { admin } }` |
| `/api/admin/admins/{id}` | DELETE | 删除管理员 | 无 | `{ success }` |
| `/api/admin/roles/{role}/permissions` | GET | 获取角色权限 | 无 | `{ success, data: { permissions: [...] } }` |
| `/api/admin/roles/{role}/permissions` | PUT | 更新角色权限 | `{ permissions: [...] }` | `{ success }` |
---
## 3. 渠道仪表板
### 文件位置
`app/channel/dashboard/page.tsx` (2091+行)
### 3.1 概览标签页 (Dashboard)
#### 功能描述
展示渠道整体运营数据和可分配Agent概览。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 总租户数 | 渠道下的租户总数 | `statsData.totalTenants` |
| 活跃租户 | 当前活跃的租户数量 | `statsData.activeTenants` |
| 月度收入 | 渠道月度收入 | `statsData.monthlyRevenue` |
| 已获佣金 | 渠道已获得的佣金 | `statsData.commission` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 统计卡片 | 核心指标 | 显示4个核心统计指标 |
| 卡片网格 | 可分配Agent | 显示各类型Agent的可分配数量 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/channel/dashboard/stats` | GET | 获取渠道统计数据 | 无 | `{ totalTenants, activeTenants, monthlyRevenue, commission }` |
| `/api/channel/agents/available` | GET | 获取可分配Agent列表 | 无 | `{ success, data: { agents: [...] } }` |
---
### 3.2 我的租户标签页 (My Tenants)
#### 功能描述
管理渠道下的租户。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 搜索框 | 搜索租户 | 按名称搜索租户 |
| 按钮 | 添加租户 | 打开创建租户对话框 |
| 列表 | 租户列表 | 显示所有租户信息 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 添加租户 | 创建新租户 | `POST /api/channel/tenants/create` |
| 查看详情 | 查看租户详情 | 本地对话框 |
| 分配资源 | 为租户分配Agent和模型 | `POST /api/channel/tenants/{id}/resources` |
| 充值 | 为租户充值 | `POST /api/channel/tenants/{id}/recharge` |
| 授信额度 | 设置租户授信额度 | `PUT /api/channel/tenants/{id}/credit-limit` |
| 管理计费 | 管理租户计费设置 | `PUT /api/channel/tenants/{id}/billing` |
| 删除租户 | 删除租户 | `DELETE /api/channel/tenants/{id}` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/channel/tenants` | GET | 获取渠道租户列表 | 无 | `{ success, data: { tenants: [...] } }` |
| `/api/channel/tenants/create` | POST | 创建租户 | `{ name, email, password, systemRole? }` | `{ success, data: { tenant } }` |
| `/api/channel/tenants/{id}` | DELETE | 删除租户 | 无 | `{ success }` |
| `/api/channel/tenants/{id}/resources` | POST | 分配租户资源 | `{ agents: [...], models: [...] }` | `{ success }` |
| `/api/channel/tenants/{id}/recharge` | POST | 租户充值 | `{ amount }` | `{ success }` |
| `/api/channel/tenants/{id}/credit-limit` | PUT | 设置授信额度 | `{ creditLimit }` | `{ success }` |
| `/api/channel/tenants/{id}/billing` | PUT | 更新计费设置 | `{ subscriptionTier, discount }` | `{ success }` |
---
### 3.3 资源管理标签页 (Resource Management)
#### 功能描述
监控已分配资源并申请新的模型或Agent。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| Agent CPU使用率 | 各Agent的CPU使用百分比 | `agent.usage.cpu` |
| Agent 内存使用率 | 各Agent的内存使用百分比 | `agent.usage.memory` |
| 可用配额 | Agent可用数量 | `agent.quantity` |
| 授权RPM | 模型每分钟请求限制 | `provider.rpm` |
| 授权TPM | 模型每分钟令牌限制 | `provider.tpm` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片网格 | Agent资源卡片 | 显示Agent计算资源和使用情况 |
| 卡片网格 | 模型供应商卡片 | 显示模型供应商和授权状态 |
| 按钮 | 提交申请 | 打开资源申请对话框 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 提交申请 | 申请新的模型或Agent资源 | `POST /api/channel/applications` |
| 申请使用 | 申请特定供应商访问权限 | `POST /api/channel/providers/{id}/apply` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/channel/providers` | GET | 获取渠道可用供应商 | 无 | `{ success, data: { providers: [...] } }` |
| `/api/channel/agents` | GET | 获取渠道Agent资源 | 无 | `{ success, data: { agents: [...] } }` |
| `/api/channel/applications` | POST | 提交资源申请 | `{ type, providerId?, agentType?, quantity?, rpm?, tpm?, reason }` | `{ success, data: { application } }` |
| `/api/channel/providers/{id}/apply` | POST | 申请供应商访问 | `{ requestedRpm, requestedTpm, reason }` | `{ success, data: { application } }` |
---
### 3.4 计费标签页 (Billing)
#### 功能描述
查看租户计费详情和调用记录。
#### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 租户调用次数 | 各租户的总调用次数 | `tenant.calls` |
| 租户EU消耗 | 各租户的EU消耗量 | `tenant.eu` |
| 租户总价 | 各租户的总消费金额 | `tenant.price` |
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片列表 | 租户计费统计 | 显示各租户的计费汇总 |
| 表格 | 调用记录明细 | 显示详细的调用记录 |
| 按钮 | 时间查询 | 打开时间范围选择 |
| 按钮 | 筛选 | 打开筛选条件对话框 |
| 按钮 | 导出 | 导出计费数据 |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/channel/billing/tenants` | GET | 获取租户计费统计 | `{ startTime?, endTime? }` | `{ success, data: { tenants: [...] } }` |
| `/api/channel/billing/calls` | GET | 获取调用记录 | `{ startTime?, endTime?, tenantId?, page?, limit? }` | `{ success, data: { calls: [...], total } }` |
| `/api/channel/billing/export` | GET | 导出计费数据 | `{ format, startTime?, endTime? }` | 文件下载 |
---
### 3.5 设置标签页 (Settings)
#### 功能描述
管理渠道管理员账户和角色权限。
#### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 列表 | 管理员列表 | 显示当前渠道的管理员 |
| 卡片 | 角色卡片 | 计费管理员/运营管理员 |
| 按钮 | 添加管理员 | 打开创建管理员对话框 |
#### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 添加管理员 | 创建渠道管理员 | `POST /api/channel/admins/create` |
| 删除管理员 | 删除管理员 | `DELETE /api/channel/admins/{id}` |
| 配置权限 | 配置角色权限 | 本地状态 |
| 保存权限 | 保存权限配置 | `PUT /api/channel/roles/{role}/permissions` |
#### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/channel/admins` | GET | 获取渠道管理员列表 | 无 | `{ success, data: { admins: [...] } }` |
| `/api/channel/admins/create` | POST | 创建渠道管理员 | `{ name, email, password, role }` | `{ success, data: { admin } }` |
| `/api/channel/admins/{id}` | DELETE | 删除管理员 | 无 | `{ success }` |
| `/api/channel/roles/{role}/permissions` | PUT | 更新角色权限 | `{ permissions: [...] }` | `{ success }` |
---
## 4. Agent工厂
### 文件位置
`app/agent-factory/page.tsx` (404行)
### 功能描述
管理平台Agent的部署和配置。
### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 可用Agent数 | 平台可用的Agent总数 | `platformAgents.length` |
| 已部署Agent数 | 已部署的Agent数量 | `deployedAgents.length` |
| CPU使用率 | 系统CPU使用百分比 | 统计数据 |
| 内存使用率 | 系统内存使用百分比 | 统计数据 |
### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 统计卡片 | 核心指标 | 显示Agent数量和资源使用 |
| 卡片网格 | 平台Agent | 显示可部署的Agent列表 |
| 卡片网格 | 已部署Agent | 显示已部署的Agent列表 |
### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 部署 | 部署Agent | `POST /api/agents/deploy` |
| 查看详情 | 查看Agent详情 | 本地对话框 |
### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/agents/platform` | GET | 获取平台Agent列表 | 无 | `{ success, data: { agents: [...] } }` |
| `/api/agents` | GET | 获取已部署Agent列表 | `{ page?, limit? }` | `{ success, data: { agents: [...], total } }` |
| `/api/agents/deploy` | POST | 部署Agent | `{ agentId, instances, model, gateway }` | `{ success, data: { deployment } }` |
| `/api/stats` | GET | 获取统计数据 | 无 | `{ success, data: { cpuUsage, memoryUsage, ... } }` |
---
## 5. 数据工具
### 文件位置
`app/data-tools/page.tsx` (606行)
### 功能描述
管理数据工具注册表和数据模板。
### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 总工具数 | 注册的工具总数 | `stats.totalTools` |
| 活跃工具 | 当前活跃的工具数 | `stats.activeTools` |
| 今日调用 | 今日工具调用次数 | `stats.todayCalls` |
| 成功率 | 工具调用成功率 | `stats.successRate` |
### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 统计卡片 | 核心指标 | 显示工具统计数据 |
| 标签切换 | 功能切换 | 工具注册表/数据模板 |
| 卡片网格 | 工具列表 | 显示已注册的工具 |
| 表单 | 数据模板配置 | JSON API/云存储/数据库配置 |
### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 注册工具 | 注册新工具 | `POST /api/tools/register` |
| 配置 | 配置工具参数 | `PUT /api/tools/{id}` |
| 删除 | 删除工具 | `DELETE /api/tools/{id}` |
| 部署Pod | 部署数据模板Pod | `POST /api/tools/deploy-pod` |
### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/tools` | GET | 获取工具列表 | 无 | `{ success, data: { tools: [...] } }` |
| `/api/tools/stats` | GET | 获取工具统计 | 无 | `{ success, data: { totalTools, activeTools, todayCalls, successRate } }` |
| `/api/tools/register` | POST | 注册工具 | `{ name, type, config }` | `{ success, data: { tool } }` |
| `/api/tools/{id}` | PUT | 更新工具配置 | `{ config }` | `{ success }` |
| `/api/tools/{id}` | DELETE | 删除工具 | 无 | `{ success }` |
| `/api/tools/deploy-pod` | POST | 部署Pod | `{ templateType, config, resources }` | `{ success, data: { pod } }` |
---
## 6. 模型网关
### 文件位置
`app/model-gateway/page.tsx` (470行)
### 功能描述
管理模型网关API和监控请求负载。
### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 总请求数 | API总请求数 | `monitoring.totalRequests` |
| 成功率 | 请求成功率 | `monitoring.successRate` |
| 平均延迟 | 平均响应延迟 | `monitoring.avgLatency` |
| 活跃连接 | 当前活跃连接数 | `monitoring.activeConnections` |
### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 统计卡片 | 监控指标 | 显示请求统计数据 |
| 标签切换 | 网关类型 | MCP/A2A/API |
| 卡片网格 | API列表 | 显示各类型的API |
| 图表 | 请求负载分布 | 显示请求负载趋势 |
### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 创建API | 创建新的网关API | `POST /api/gateway/apis` |
| 配置 | 配置API参数 | `PUT /api/gateway/apis/{id}` |
| 删除 | 删除API | `DELETE /api/gateway/apis/{id}` |
### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/gateway/apis` | GET | 获取网关API列表 | 无 | `{ success, data: { apis: [...] } }` |
| `/api/gateway/apis` | POST | 创建网关API | `{ name, method, content, type }` | `{ success, data: { api } }` |
| `/api/gateway/apis/{id}` | PUT | 更新API配置 | `{ name, method, content }` | `{ success }` |
| `/api/gateway/apis/{id}` | DELETE | 删除API | 无 | `{ success }` |
| `/api/gateway/monitoring` | GET | 获取监控数据 | 无 | `{ success, data: { totalRequests, successRate, avgLatency, activeConnections, loadDistribution } }` |
| `/api/gateway/providers` | GET | 获取模型提供商 | 无 | `{ success, data: { providers: [...] } }` |
---
## 7. 编排中心
### 文件位置
`app/orchestration/page.tsx` (419行)
### 功能描述
创建和管理Agent工作流编排。
### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 卡片网格 | 工作流列表 | 显示已创建的工作流 |
| 按钮 | 创建工作流 | 打开工作流创建对话框 |
| 选择器 | 服务网关 | 选择MCP/A2A/API网关 |
| 节点编辑器 | 工作流节点 | 配置工作流节点(最多3个) |
### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 创建工作流 | 创建新工作流 | `POST /api/workflows` |
| 编辑 | 编辑工作流 | `PUT /api/workflows/{id}` |
| 删除 | 删除工作流 | `DELETE /api/workflows/{id}` |
| 运行 | 运行工作流 | `POST /api/workflows/{id}/run` |
### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/workflows` | GET | 获取工作流列表 | 无 | `{ success, data: { workflows: [...] } }` |
| `/api/workflows` | POST | 创建工作流 | `{ name, gateway, nodes: [...] }` | `{ success, data: { workflow } }` |
| `/api/workflows/{id}` | PUT | 更新工作流 | `{ name, gateway, nodes }` | `{ success }` |
| `/api/workflows/{id}` | DELETE | 删除工作流 | 无 | `{ success }` |
| `/api/workflows/{id}/run` | POST | 运行工作流 | `{ input? }` | `{ success, data: { result } }` |
| `/api/agents/platform` | GET | 获取平台Agent列表 | 无 | `{ success, data: { agents: [...] } }` |
---
## 8. 计费中心
### 文件位置
`app/billing/page.tsx` (527行)
### 功能描述
用户计费管理,包括余额查询、充值和消费历史。
### 监控指标
| 指标名称 | 描述 | 数据来源 |
|---------|------|---------|
| 当前余额 | 用户当前账户余额 | `balance.current` |
| 本月消费 | 本月累计消费金额 | `balance.monthlySpent` |
| 剩余额度 | 剩余可用额度 | `balance.remaining` |
### 页面元素
| 元素类型 | 名称 | 描述 |
|---------|------|------|
| 余额卡片 | 账户余额 | 显示当前余额和消费情况 |
| 按钮 | 充值 | 打开充值对话框 |
| 图表 | EU消费历史 | 显示消费趋势图表 |
| 表格 | 费用明细 | 显示详细消费记录 |
| 卡片 | 资源使用 | 显示各资源使用情况 |
### 按钮操作
| 按钮名称 | 操作描述 | 触发接口 |
|---------|---------|---------|
| 充值 | 账户充值 | `POST /api/billing/recharge` |
| 导出 | 导出账单 | `GET /api/billing/export` |
### 所需后端接口
| 接口路径 | 方法 | 描述 | 请求参数 | 响应数据 |
|---------|------|------|---------|---------|
| `/api/billing/balance` | GET | 获取账户余额 | 无 | `{ success, data: { current, monthlySpent, remaining, creditLimit } }` |
| `/api/billing/history` | GET | 获取消费历史 | `{ startTime?, endTime? }` | `{ success, data: { records: [...], chart: [...] } }` |
| `/api/billing/recharge` | POST | 账户充值 | `{ amount }` | `{ success, data: { transaction } }` |
| `/api/billing/export` | GET | 导出账单 | `{ format, startTime?, endTime? }` | 文件下载 |
---
## 9. 接口汇总表
### 9.1 认证接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/auth/login` | POST | 用户登录 | 高 |
| `/api/auth/logout` | POST | 用户登出 | 高 |
| `/api/auth/refresh` | POST | 刷新Token | 高 |
### 9.2 超级管理员接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/admin/dashboard/stats` | GET | 获取仪表板统计 | 高 |
| `/api/admin/channels` | GET | 获取渠道列表 | 高 |
| `/api/admin/channels/create` | POST | 创建渠道 | 高 |
| `/api/admin/channels/{id}` | GET | 获取渠道详情 | 中 |
| `/api/admin/channels/{id}` | PUT | 更新渠道 | 中 |
| `/api/admin/channels/{id}` | DELETE | 删除渠道 | 中 |
| `/api/admin/channels/{id}/resources` | GET | 获取渠道资源 | 中 |
| `/api/admin/channels/{id}/resources` | PUT | 更新渠道资源 | 中 |
| `/api/admin/channels/{id}/provider-access` | GET | 获取渠道授权 | 中 |
| `/api/admin/channels/provider-access/{id}` | DELETE | 撤销授权 | 中 |
| `/api/admin/tenants` | GET | 获取租户列表 | 高 |
| `/api/admin/applications` | GET | 获取申请列表 | 中 |
| `/api/admin/applications/{id}/review` | POST | 审批申请 | 中 |
| `/api/admin/agents` | GET | 获取Agent资源 | 高 |
| `/api/admin/agents/{id}` | PUT | 更新Agent | 中 |
| `/api/admin/agents/{id}` | DELETE | 删除Agent | 中 |
| `/api/admin/providers` | GET | 获取供应商列表 | 高 |
| `/api/admin/providers/create` | POST | 创建供应商 | 中 |
| `/api/admin/providers/{id}` | PUT | 更新供应商 | 中 |
| `/api/admin/providers/{id}` | DELETE | 删除供应商 | 中 |
| `/api/admin/providers/{id}/test` | POST | 测试供应商 | 低 |
| `/api/admin/monitoring/agents` | GET | 获取Agent监控 | 高 |
| `/api/admin/billing/overview` | GET | 获取计费概览 | 中 |
| `/api/admin/admins` | GET | 获取管理员列表 | 中 |
| `/api/admin/admins/create` | POST | 创建管理员 | 中 |
| `/api/admin/admins/{id}` | DELETE | 删除管理员 | 中 |
| `/api/admin/roles/{role}/permissions` | GET | 获取角色权限 | 低 |
| `/api/admin/roles/{role}/permissions` | PUT | 更新角色权限 | 低 |
### 9.3 渠道接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/channel/dashboard/stats` | GET | 获取渠道统计 | 高 |
| `/api/channel/tenants` | GET | 获取租户列表 | 高 |
| `/api/channel/tenants/create` | POST | 创建租户 | 高 |
| `/api/channel/tenants/{id}` | DELETE | 删除租户 | 中 |
| `/api/channel/tenants/{id}/resources` | POST | 分配资源 | 中 |
| `/api/channel/tenants/{id}/recharge` | POST | 租户充值 | 中 |
| `/api/channel/tenants/{id}/credit-limit` | PUT | 设置授信 | 中 |
| `/api/channel/tenants/{id}/billing` | PUT | 更新计费 | 中 |
| `/api/channel/tenants/{id}/permissions` | PUT | 更新权限 | 中 |
| `/api/channel/tenants/{id}/password` | PUT | 修改密码 | 中 |
| `/api/channel/tenants/{id}/status` | PUT | 更新状态 | 中 |
| `/api/channel/providers` | GET | 获取供应商 | 高 |
| `/api/channel/agents` | GET | 获取Agent | 高 |
| `/api/channel/applications` | POST | 提交申请 | 中 |
| `/api/channel/providers/{id}/apply` | POST | 申请供应商 | 中 |
| `/api/channel/billing/tenants` | GET | 租户计费 | 中 |
| `/api/channel/billing/calls` | GET | 调用记录 | 中 |
| `/api/channel/billing/export` | GET | 导出账单 | 低 |
| `/api/channel/admins` | GET | 获取管理员 | 中 |
| `/api/channel/admins/create` | POST | 创建管理员 | 中 |
| `/api/channel/admins/{id}` | DELETE | 删除管理员 | 中 |
### 9.4 Agent和工具接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/agents/platform` | GET | 平台Agent列表 | 高 |
| `/api/agents` | GET | 已部署Agent | 高 |
| `/api/agents/deploy` | POST | 部署Agent | 高 |
| `/api/tools` | GET | 工具列表 | 高 |
| `/api/tools/stats` | GET | 工具统计 | 中 |
| `/api/tools/register` | POST | 注册工具 | 中 |
| `/api/tools/{id}` | PUT | 更新工具 | 中 |
| `/api/tools/{id}` | DELETE | 删除工具 | 中 |
| `/api/tools/deploy-pod` | POST | 部署Pod | 中 |
### 9.5 网关和工作流接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/gateway/apis` | GET | 获取API列表 | 高 |
| `/api/gateway/apis` | POST | 创建API | 中 |
| `/api/gateway/apis/{id}` | PUT | 更新API | 中 |
| `/api/gateway/apis/{id}` | DELETE | 删除API | 中 |
| `/api/gateway/monitoring` | GET | 获取监控 | 高 |
| `/api/gateway/providers` | GET | 获取提供商 | 中 |
| `/api/workflows` | GET | 工作流列表 | 高 |
| `/api/workflows` | POST | 创建工作流 | 中 |
| `/api/workflows/{id}` | PUT | 更新工作流 | 中 |
| `/api/workflows/{id}` | DELETE | 删除工作流 | 中 |
| `/api/workflows/{id}/run` | POST | 运行工作流 | 中 |
### 9.6 计费接口
| 接口路径 | 方法 | 描述 | 优先级 |
|---------|------|------|-------|
| `/api/billing/balance` | GET | 获取余额 | 高 |
| `/api/billing/history` | GET | 消费历史 | 高 |
| `/api/billing/recharge` | POST | 充值 | 高 |
| `/api/billing/export` | GET | 导出账单 | 低 |
---
## 附录:数据模型参考
### 用户角色
- `user` - 普通用户/租户
- `channel` - 渠道管理员
- `billing_admin` - 计费管理员
- `operations_admin` - 运营管理员
- `super_admin` - 超级管理员
### 服务网关类型
- `MCP` - Model Context Protocol
- `A2A` - Agent to Agent
- `API` - 标准REST API
### 订阅等级
- `free` - 免费版
- `starter` - 入门版
- `professional` - 专业版
- `enterprise` - 企业版
### EU计算规则
- 1 EU = 10秒调用时间
- 单价:¥0.10/EU
---
*文档生成时间:2025-12-31*
*基于前端代码版本:taiji-pad-v0*
+1
View File
@@ -0,0 +1 @@
api-client.ts
+115
View File
@@ -417,6 +417,16 @@ export class TaijiAPIClient {
return handleResponse(response)
}
/**
* 获取工作流列表
*/
static async getWorkflows() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/workflows`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 创建工作流
*/
@@ -1088,6 +1098,30 @@ export class TaijiAPIClient {
return handleResponse(response)
}
/**
* 获取所有租户列表(超级管理员)
* GET /api/admin/tenants
*/
static async getAdminTenants() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/tenants`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 修改租户密码(渠道管理员或超级管理员)
* PUT /api/channel/tenants/{tenant_id}/password
*/
static async changeTenantPassword(tenantId: string, newPassword: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/password`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify({ new_password: newPassword }),
})
return handleResponse(response)
}
// ==================== 供应商管理 API ====================
// Base URL: http://localhost:8002/api/providers
@@ -1419,6 +1453,87 @@ export class TaijiAPIClient {
return handleResponse(response)
}
// ==================== K8s Agent 管理 API ====================
// Base URL: http://localhost:8002/agents
/**
* 获取所有可用的 Agent 模板及其所需参数
* GET /agents/templates
* 此接口无需认证
*/
static async getAgentTemplates() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/templates`)
return handleResponse(response)
}
/**
* 获取指定模板的详细信息
* GET /agents/templates/{template_name}
* 此接口无需认证
*/
static async getAgentTemplateDetail(templateName: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/templates/${templateName}`)
return handleResponse(response)
}
/**
* 创建 K8s Agent
* POST /agents
* 如果指定了 template,将在 Kubernetes 中创建对应的 Pod
*/
static async createK8sAgent(data: {
name: string
description?: string
template?: string
resource_config?: {
cpu_request?: string
cpu_limit?: string
memory_request?: string
memory_limit?: string
replicas?: number
env?: Record<string, string>
}
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents`, {
method: "POST",
headers: buildHeaders("application/json", true),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 删除 Agent
* DELETE /agents/{agent_id}
* 如果 Agent 有关联的 K8s Pod,也会一并删除
*/
static async deleteAgent(agentId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/${agentId}`, {
method: "DELETE",
headers: buildHeaders("application/json", true),
})
return handleResponse(response)
}
/**
* 获取 Agent 的实时状态
* GET /agents/{agent_id}/status
* 如果 Agent 有关联的 K8s Pod,会从 Agent Manager 获取最新状态
*/
static async getAgentStatus(agentId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/${agentId}/status`)
return handleResponse(response)
}
/**
* 获取 Agent 的 CPU 和内存资源配置信息
* GET /agents/{agent_id}/metrics
*/
static async getAgentMetrics(agentId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/${agentId}/metrics`)
return handleResponse(response)
}
/**
* 获取 MCP Prometheus Metrics
*/