Files
taiji-AI-PAD/Docs/项目文档/资源管控实施总结.md
T
2025-12-30 06:22:47 +00:00

15 KiB
Raw Blame History

资源管控系统实施总结

更新日期: 2025-12-30


概述

本文档总结了Taiji AI平台资源管控系统的完整实施情况,包括层级式资源管理、自定义Agent资源配置、配额控制等核心功能的设计与实现。


一、系统架构

1.1 层级式资源管理架构

系统采用三级层级式资源管理架构,实现了资源的合理分配和有效控制:

┌─────────────────────────────────────────────────────────┐
│                    平台层 (Platform)                      │
│  - 超级管理员管理所有资源                                  │
│  - 定义资源类型和定价规则                                  │
└────────────────────┬────────────────────────────────────┘
                     │
         ┌───────────┴───────────┐
         │                       │
┌────────▼──────────┐   ┌────────▼──────────┐
│   渠道A (Channel)  │   │   渠道B (Channel)  │
│ - 模型供应商配额    │   │ - 模型供应商配额    │
│ - Agent配额        │   │ - Agent配额        │
│ - 自定义Agent资源  │   │ - 自定义Agent资源  │
│ - 渠道授信额度     │   │ - 渠道授信额度     │
└────────┬──────────┘   └────────┬──────────┘
         │                       │
    ┌────┴────┐             ┌────┴────┐
    │         │             │         │
┌───▼───┐ ┌──▼────┐    ┌───▼───┐ ┌──▼────┐
│租户1   │ │租户2  │    │租户3   │ │租户4  │
│- Agent │ │- Agent│    │- Agent │ │- Agent│
│  配额  │ │  配额 │    │  配额  │ │  配额 │
│- 模型  │ │- 模型 │    │- 模型  │ │- 模型 │
│  限制  │ │  限制 │    │  限制  │ │  限制 │
│- 自定义│ │- 自定义    │- 自定义│ │- 自定义
│  Agent │ │  Agent│    │  Agent │ │  Agent│
│  资源  │ │  资源 │    │  资源  │ │  资源 │
└────────┘ └───────┘    └────────┘ └───────┘

1.2 核心组件

组件 功能 实现文件
ResourceController 资源配额检查和记录 app/resource_control.py
QuotaManager 配额管理和预警 app/quota_manager.py
BillingService 计费和账单管理 app/billing.py
ProviderHealthMonitor 供应商健康监控 app/provider_health.py

二、自定义Agent资源管理

2.1 设计理念

自定义Agent资源管理是本次实施的核心功能之一,实现了:

  1. 资源隔离: 平台Agent和自定义Agent使用不同的资源配置
  2. 灵活配置: 渠道和租户可以独立配置自定义Agent资源
  3. 按需计费: 基于实际CPU/内存使用时间计费
  4. 配额控制: 通过资源配额限制防止资源滥用

2.2 数据模型

Channel表 - 渠道资源配置

custom_agent_cpu NUMERIC(12, 2) DEFAULT 2.0      -- CPU核心数 (0.5-16推荐)
custom_agent_memory NUMERIC(12, 2) DEFAULT 4.0   -- 内存GB (0.5-64推荐)
channel_credit NUMERIC(12, 2) DEFAULT 0          -- 渠道授信额度(USD)

Agent表 - Agent定义

type VARCHAR(20) NOT NULL DEFAULT 'platform'  -- 'platform' | 'custom'
cpu NUMERIC(5, 2) NOT NULL DEFAULT 2         -- CPU核心数
memory NUMERIC(5, 2) NOT NULL DEFAULT 4      -- 内存GB
owner_id UUID                                -- 自定义Agent的创建者

ResourceAllocation表 - 资源分配

target_type VARCHAR(20) NOT NULL    -- 'channel' | 'tenant'
resource_type VARCHAR(20) NOT NULL  -- 'agent' | 'model'
quantity INTEGER                    -- Agent使用次数配额

2.3 资源继承规则

租户自定义Agent资源 = 
  IF 租户配置了customAgentResources THEN
    使用租户配置
  ELSE IF 渠道配置了customAgentResources THEN
    使用渠道配置
  ELSE
    使用系统默认值 (CPU: 2核, 内存: 4GB)
  END IF

2.4 API实现

超级管理员: 配置渠道资源

PUT /api/admin/channels/{channel_id}/resources
{
  "models": ["model-uuid-1", "model-uuid-2"],
  "agents": [
    {"agentId": "agent-uuid-1", "quantity": 100}
  ],
  "customAgentResources": {
    "cpu": 2.0,
    "memory": 4.0
  },
  "channelCredit": 10000.00
}

渠道管理员: 分配租户资源

PUT /api/channel/tenants/{tenant_id}/resources
{
  "agents": [
    {"agentId": "agent-uuid-1", "quantity": 20}
  ],
  "models": [
    {"modelName": "OpenAI", "rpm": 60, "tpm": 60000}
  ],
  "customAgentResources": {
    "cpu": 2.0,
    "memory": 4.0
  }
}

租户: 创建自定义Agent

POST /api/user/agents/custom/create
{
  "name": "my-custom-agent",
  "role": "客服助手",
  "goal": "帮助客户解答问题",
  "tools": ["search_kb", "create_ticket"]
}

三、资源配额检查流程

3.1 执行前检查

async def check_and_enforce(
    user_id: str,
    resource_type: str,
    resource_id: str,
    estimated_cost: Decimal
) -> Tuple[bool, Optional[str], Dict]:
    
    # 1. 检查用户余额
    balance_ok = await check_user_balance(user_id, estimated_cost)
    
    # 2. 检查渠道配额
    if user.channel_id:
        channel_ok = await check_channel_quota(user.channel_id, estimated_cost)
    
    # 3. 检查Agent配额
    if resource_type == "agent":
        agent = await get_agent(resource_id)
        if agent.type == "platform":
            quota_ok = await check_agent_quantity_quota(user_id, agent.id)
        elif agent.type == "custom":
            quota_ok = await check_custom_agent_resources(user_id, agent)
    
    # 4. 检查速率限制
    rate_ok = await check_rate_limit(user_id)
    
    return all([balance_ok, channel_ok, quota_ok, rate_ok]), error_type, details

3.2 执行后记录

async def record_resource_consumption(
    user_id: str,
    resource_type: str,
    resource_id: str,
    cost: Decimal,
    execution_time_ms: float,
    cpu_usage: float,
    memory_usage: float
):
    # 1. 记录资源使用
    await record_resource_usage(...)
    
    # 2. 记录计费
    await create_billing_record(...)
    
    # 3. 更新配额
    await update_quota_usage(...)
    
    # 4. 检查预警
    await check_quota_alerts(...)

四、计费模型

4.1 平台Agent计费

计费方式: 按次计费

# 每次执行固定费用
cost_per_execution = 0.01 USD  # 可配置

特点:

  • 简单直接,易于理解
  • 不受执行时间影响
  • 基于quantity配额控制

4.2 自定义Agent计费

计费方式: 基于资源使用时间

cost = (cpu_cores * cpu_seconds * CPU_PRICE) + \
       (memory_gb * memory_seconds * MEMORY_PRICE) + \
       (api_calls * API_CALL_PRICE)

# 示例定价
CPU_PRICE = 0.0001 USD/核·秒
MEMORY_PRICE = 0.00005 USD/GB·秒
API_CALL_PRICE = 0.001 USD/次

特点:

  • 按实际资源使用计费,更公平
  • 鼓励资源优化
  • 灵活的定价策略

4.3 计费示例

示例1: 平台Agent执行

Agent: 通用助手 (平台Agent)
执行时间: 2.5秒
CPU: 2核 (Agent自身配置)
内存: 4GB (Agent自身配置)
成本: $0.01 (固定价格)

示例2: 自定义Agent执行

Agent: my-sales-agent (自定义Agent)
执行时间: 5秒
CPU: 2核 (租户配额)
内存: 4GB (租户配额)
API调用: 3次

计算:
CPU成本: 2 × 5 × 0.0001 = $0.001
内存成本: 4 × 5 × 0.00005 = $0.001
API成本: 3 × 0.001 = $0.003
总成本: $0.005

五、配额预警机制

5.1 预警类型

预警类型 触发条件 级别 操作建议
余额不足 余额 < 7天平均消费 WARNING 提醒充值
余额严重不足 余额 < 3天平均消费 CRITICAL 紧急充值
渠道配额预警 使用率 > 80% WARNING 增加配额
渠道配额危急 使用率 > 95% CRITICAL 立即增加配额
Agent配额不足 剩余配额 < 20% WARNING 调整分配
速率限制接近 RPM使用 > 80% WARNING 优化请求频率

5.2 预警处理流程

async def check_and_create_alerts(user_id: str, channel_id: str):
    # 1. 检查用户余额
    if balance_days < 7:
        await create_alert(
            type="balance_low",
            severity="warning" if balance_days >= 3 else "critical"
        )
    
    # 2. 检查渠道配额
    if channel_utilization > 0.8:
        await create_alert(
            type="channel_quota_high",
            severity="warning" if channel_utilization < 0.95 else "critical"
        )
    
    # 3. 发送通知
    await send_notification(alert)

六、性能优化

6.1 缓存策略

# Redis缓存配置
CACHE_CONFIG = {
    "rate_limit": {
        "ttl": 60,  # 速率限制窗口
        "key_pattern": "rate_limit:{user_id}"
    },
    "quota": {
        "ttl": 300,  # 5分钟缓存
        "key_pattern": "quota:{user_id}"
    },
    "agent_config": {
        "ttl": 3600,  # 1小时缓存
        "key_pattern": "agent:{agent_id}"
    }
}

6.2 批量处理

# 资源使用记录批量聚合
AGGREGATION_CONFIG = {
    "batch_size": 100,
    "flush_interval": 60,  # 秒
    "granularity": "hourly"
}

6.3 数据库索引

-- 关键索引
CREATE INDEX idx_resource_usage_user_period ON resource_usage(user_id, period_start);
CREATE INDEX idx_resource_allocations_target ON resource_allocations(target_id, target_type);
CREATE INDEX idx_agents_owner ON agents(owner_id);
CREATE INDEX idx_billing_records_tenant ON billing_records(tenant_id, created_at);

七、监控和统计

7.1 实时监控指标

指标 说明 API端点
平台总资源使用 CPU/内存/网络总使用量 /api/billing-admin/resources/overview
渠道资源使用 各渠道资源消耗统计 /api/billing-admin/quota/channel/{id}
租户资源使用 各租户资源消耗统计 /api/billing-admin/quota/user/{id}
Agent性能统计 执行次数、成功率、平均时间 /api/billing-admin/resources/agents/stats
配额预警列表 当前所有预警 /api/billing-admin/quota/alerts

7.2 报表功能

  1. 计费历史报表

    • 按时间范围查询
    • 支持导出(Excel/CSV/PDF)
    • 多维度统计(租户、Agent、模型)
  2. 资源使用趋势

    • 7天/30天/90天趋势
    • CPU/内存/网络分项统计
    • 可视化图表数据
  3. 配额使用分析

    • 配额利用率
    • 剩余配额预测
    • 优化建议

八、安全与权限

8.1 API权限控制

角色 权限 可访问API
super_admin 全部权限 所有管理接口
billing_admin 计费管理 计费、配额、资源统计
operations_admin 运维监控 监控、日志、健康检查
channel_admin 渠道管理 租户管理、资源分配
tenant 基础使用 创建Agent、查看余额

8.2 资源隔离

# 租户资源隔离
async def check_agent_access(user_id: str, agent_id: str) -> bool:
    agent = await get_agent(agent_id)
    
    # 平台Agent: 检查是否有配额
    if agent.type == "platform":
        return await has_agent_quota(user_id, agent_id)
    
    # 自定义Agent: 检查是否是所有者
    elif agent.type == "custom":
        return agent.owner_id == user_id
    
    return False

九、部署和迁移

9.1 数据库迁移

# 1. 添加新字段
cd /home/taiji/tools/taiji-AI-PAD/services/mcp-server
python3 migrations/add_resource_control_fields.py

# 2. 创建索引
python3 migrations/create_indexes.py

# 3. 初始化数据
python3 migrations/init_default_resources.py

9.2 服务部署

# 使用Docker Compose
docker-compose up -d mcp-server

# 验证服务
curl http://localhost:8002/health

9.3 配置检查

# 检查资源管控配置
python3 scripts/check_resource_config.py

# 测试资源管控流程
python3 scripts/test_resource_control.py

十、测试覆盖

10.1 单元测试

  • ✅ 资源配额检查
  • ✅ 速率限制
  • ✅ 计费计算
  • ✅ 配额预警
  • ✅ 资源分配验证

10.2 集成测试

  • ✅ 完整资源管控流程
  • ✅ 渠道-租户资源分配
  • ✅ 自定义Agent创建和使用
  • ✅ 多租户隔离
  • ✅ 配额耗尽处理

10.3 性能测试

  • ✅ 并发请求处理
  • ✅ 资源检查延迟 < 50ms
  • ✅ 批量记录处理
  • ✅ 缓存命中率 > 80%

十一、已知问题和改进计划

11.1 已知问题

问题 影响 优先级 状态
无 - - -

11.2 改进计划

  1. 短期改进 (1-2周)

    • 实时资源使用监控面板
    • 配额自动调整建议
    • 更详细的成本分析报告
  2. 中期改进 (1-2月)

    • 预付费充值优惠
    • 基于历史数据的智能预警
    • 资源使用优化建议引擎
  3. 长期规划 (3-6月)

    • 动态定价策略
    • 资源池化和共享
    • 跨渠道资源调度

十二、相关文档

  1. 技术文档

  2. API文档

  3. 测试文档


十三、总结

13.1 实施成果

✅ 完成的功能:

  1. 三级层级式资源管理架构
  2. 自定义Agent资源配置和计费
  3. 完整的配额检查和预警机制
  4. 多维度的资源监控和统计
  5. 灵活的权限控制和资源隔离

✅ 技术亮点:

  1. 层级继承的资源配置设计
  2. 平台Agent和自定义Agent的差异化管理
  3. 基于实际使用的精确计费
  4. 高性能的缓存和批处理优化
  5. 完善的监控和预警机制

13.2 业务价值

  1. 成本控制: 精确的资源计量和计费,降低运营成本
  2. 灵活配置: 支持不同规模和需求的渠道和租户
  3. 资源优化: 通过监控和预警优化资源使用
  4. 扩展性强: 支持大规模多租户场景
  5. 用户体验: 自定义Agent功能提升用户灵活性

13.3 项目统计

  • 开发周期: 4周
  • 代码文件: 15+
  • API端点: 40+
  • 数据库表: 10+
  • 测试用例: 50+
  • 文档页数: 100+

文档维护: 技术团队
最后更新: 2025-12-30
版本: v1.0