Files
taiji-AI-PAD/Docs/项目文档/API接口文档_监控功能.md
T
xiaohei 70608bed16 feat: 实现平台监控功能并生成API文档
功能实现:
1. 创建监控模块 (monitoring.py)
   - 系统健康检查
   - 系统性能指标(CPU、内存、磁盘)
   - 服务统计信息(Agent、执行、工具、用户)
   - 性能趋势分析
   - 系统告警

2. 添加监控API端点
   - GET /api/v1/monitoring/metrics - 系统性能指标
   - GET /api/v1/monitoring/stats - 服务统计信息
   - GET /api/v1/monitoring/trends - 性能趋势数据
   - GET /api/v1/monitoring/alerts - 系统告警
   - GET /api/v1/monitoring/dashboard - 监控仪表板

3. 优化健康检查API
   - 使用监控模块统一管理健康检查

4. 添加依赖
   - psutil==5.9.6 (系统资源监控)

5. 生成API文档
   - Docs/项目文档/API接口文档_监控功能.md
   - 包含完整的API说明、请求/响应示例、集成示例

监控功能:
- 实时系统资源监控(CPU、内存、磁盘)
- 服务指标统计(24小时/7天)
- 性能趋势分析(支持多种时间范围和间隔)
- 智能告警系统(资源告警、服务告警)
- 聚合监控仪表板
2025-12-23 07:36:57 +00:00

17 KiB
Raw Blame History

taiji-AI-PAD API 接口文档 - 监控功能

版本: v2.0
创建时间: 2025年12月23日
最后更新: 2025年12月23日


📋 目录

  1. 概述
  2. 基础信息
  3. 监控API端点
  4. 请求/响应示例
  5. 错误处理
  6. 集成示例

1. 概述

本文档描述了 taiji-AI-PAD 平台监控功能的 API 接口。监控功能提供系统健康检查、性能指标、资源使用、服务统计、性能趋势和系统告警等功能。

1.1 功能特性

  • ✅ 系统健康检查
  • ✅ 实时性能指标(CPU、内存、磁盘)
  • ✅ 服务统计信息(Agent、执行、工具、用户)
  • ✅ 性能趋势分析
  • ✅ 系统告警
  • ✅ 监控仪表板(聚合数据)

1.2 监控指标

  • 系统资源: CPU使用率、内存使用、磁盘使用
  • 服务指标: 活跃Agent数、执行次数、成功率、平均响应时间
  • 业务指标: 日活用户、EU消耗、成本统计
  • 告警信息: 资源告警、服务告警

2. 基础信息

2.1 基础URL

http://localhost:8002

2.2 认证方式

当前版本无需认证,未来版本将支持 JWT Token 认证。

2.3 响应格式

所有API响应均为 JSON 格式,使用 UTF-8 编码。

2.4 HTTP状态码

状态码 说明
200 请求成功
400 请求参数错误
500 服务器内部错误

3. 监控API端点

3.1 系统健康检查

GET /health

获取系统健康状态。

请求参数: 无

响应示例:

{
  "status": "healthy",
  "timestamp": "2025-12-23T07:30:00.000000",
  "services": {
    "database": "healthy",
    "redis": "healthy",
    "nats": "healthy"
  }
}

响应字段说明:

  • status: 系统整体状态 (healthy, degraded, unhealthy)
  • timestamp: 检查时间戳
  • services: 各服务健康状态

3.2 系统性能指标

GET /api/v1/monitoring/metrics

获取系统实时性能指标。

请求参数: 无

响应示例:

{
  "timestamp": "2025-12-23T07:30:00.000000",
  "system": {
    "cpu_usage_percent": 15.5,
    "memory_usage_percent": 45.2,
    "memory_used_mb": 2048.5,
    "memory_total_mb": 4096.0,
    "disk_usage_percent": 32.1,
    "disk_used_gb": 128.5,
    "disk_total_gb": 400.0
  },
  "services": {
    "active_agents": 10,
    "total_executions_24h": 1250,
    "success_rate_percent": 98.5,
    "avg_execution_time_ms": 125.5,
    "daily_active_users": 25
  },
  "billing": {
    "total_eu_consumed_24h": 1250.5,
    "total_cost_24h": 12.50
  }
}

响应字段说明:

  • system: 系统资源使用情况
    • cpu_usage_percent: CPU使用率(%)
    • memory_usage_percent: 内存使用率(%)
    • memory_used_mb: 已使用内存(MB)
    • memory_total_mb: 总内存(MB)
    • disk_usage_percent: 磁盘使用率(%)
    • disk_used_gb: 已使用磁盘(GB)
    • disk_total_gb: 总磁盘空间(GB)
  • services: 服务指标(过去24小时)
    • active_agents: 活跃Agent数量
    • total_executions_24h: 总执行次数
    • success_rate_percent: 成功率(%)
    • avg_execution_time_ms: 平均执行时间(毫秒)
    • daily_active_users: 日活用户数
  • billing: 计费统计(过去24小时)
    • total_eu_consumed_24h: 总EU消耗
    • total_cost_24h: 总成本

3.3 服务统计信息

GET /api/v1/monitoring/stats

获取服务统计信息。

请求参数:

参数名 类型 必填 说明
service string 否 服务类型,可选值: all, agents, executions, tools, users,默认: all

请求示例:

GET /api/v1/monitoring/stats?service=agents

响应示例:

{
  "timestamp": "2025-12-23T07:30:00.000000",
  "stats": {
    "agents": {
      "total": 50,
      "active": 45,
      "inactive": 5,
      "avg_executions": 125.5,
      "avg_success_rate": 98.2
    },
    "executions": {
      "total_7d": 8750,
      "completed": 8600,
      "failed": 100,
      "running": 50,
      "avg_time_ms": 125.5,
      "total_eu": 8750.5
    },
    "tools": {
      "total": 20,
      "active": 18,
      "total_calls": 12500,
      "avg_success_rate": 99.5,
      "avg_response_time_ms": 50.2
    },
    "users": {
      "total": 100,
      "active": 95,
      "admins": 5
    }
  }
}

响应字段说明:

  • agents: Agent统计
    • total: 总Agent数
    • active: 活跃Agent数
    • inactive: 非活跃Agent数
    • avg_executions: 平均执行次数
    • avg_success_rate: 平均成功率
  • executions: 执行统计(过去7天)
    • total_7d: 总执行次数
    • completed: 成功完成数
    • failed: 失败数
    • running: 运行中数
    • avg_time_ms: 平均执行时间(毫秒)
    • total_eu: 总EU消耗
  • tools: 工具统计
    • total: 总工具数
    • active: 活跃工具数
    • total_calls: 总调用次数
    • avg_success_rate: 平均成功率
    • avg_response_time_ms: 平均响应时间(毫秒)
  • users: 用户统计
    • total: 总用户数
    • active: 活跃用户数
    • admins: 管理员数

3.4 性能趋势数据

GET /api/v1/monitoring/trends

获取性能趋势数据。

请求参数:

参数名 类型 必填 说明
metric string 否 指标类型,可选值: executions, eu_consumption,默认: executions
period string 否 时间范围,可选值: 24h, 7d, 30d,默认: 24h
interval string 否 时间间隔,可选值: 1h, 6h, 1d,默认: 1h

请求示例:

GET /api/v1/monitoring/trends?metric=executions&period=7d&interval=6h

响应示例 (metric=executions):

{
  "metric": "executions",
  "period": "7d",
  "interval": "6h",
  "data": [
    {
      "timestamp": "2025-12-23T00:00:00",
      "count": 125,
      "avg_time_ms": 120.5,
      "success_rate": 98.5
    },
    {
      "timestamp": "2025-12-23T06:00:00",
      "count": 150,
      "avg_time_ms": 125.2,
      "success_rate": 99.0
    }
  ]
}

响应示例 (metric=eu_consumption):

{
  "metric": "eu_consumption",
  "period": "24h",
  "interval": "1h",
  "data": [
    {
      "timestamp": "2025-12-23T00:00:00",
      "eu_consumed": 50.5,
      "cost": 0.50
    },
    {
      "timestamp": "2025-12-23T01:00:00",
      "eu_consumed": 52.3,
      "cost": 0.52
    }
  ]
}

响应字段说明:

  • metric: 指标类型
  • period: 时间范围
  • interval: 时间间隔
  • data: 趋势数据数组
    • timestamp: 时间点
    • count: 执行次数(executions指标)
    • avg_time_ms: 平均执行时间(executions指标)
    • success_rate: 成功率(executions指标)
    • eu_consumed: EU消耗(eu_consumption指标)
    • cost: 成本(eu_consumption指标)

3.5 系统告警

GET /api/v1/monitoring/alerts

获取系统告警信息。

请求参数:

参数名 类型 必填 说明
severity string 否 严重程度过滤,可选值: warning, critical, info

请求示例:

GET /api/v1/monitoring/alerts?severity=critical

响应示例:

{
  "timestamp": "2025-12-23T07:30:00.000000",
  "alerts": [
    {
      "severity": "warning",
      "type": "high_cpu",
      "message": "CPU使用率过高: 85.5%",
      "timestamp": "2025-12-23T07:29:00.000000"
    },
    {
      "severity": "critical",
      "type": "low_disk",
      "message": "磁盘空间不足: 92.1%",
      "timestamp": "2025-12-23T07:25:00.000000"
    }
  ],
  "count": 2
}

响应字段说明:

  • timestamp: 查询时间
  • alerts: 告警列表
    • severity: 严重程度 (warning, critical, info)
    • type: 告警类型 (high_cpu, high_memory, low_disk, high_failure_rate)
    • message: 告警消息
    • timestamp: 告警时间
  • count: 告警总数

告警类型说明:

  • high_cpu: CPU使用率 > 80%
  • high_memory: 内存使用率 > 85%
  • low_disk: 磁盘使用率 > 90%
  • high_failure_rate: 过去1小时内失败执行 > 10次

3.6 监控仪表板

GET /api/v1/monitoring/dashboard

获取监控仪表板数据(聚合所有监控信息)。

请求参数: 无

响应示例:

{
  "timestamp": "2025-12-23T07:30:00.000000",
  "health": {
    "status": "healthy",
    "timestamp": "2025-12-23T07:30:00.000000",
    "uptime_seconds": 86400,
    "services": {
      "database": "healthy",
      "redis": "healthy",
      "nats": "healthy"
    }
  },
  "metrics": {
    "timestamp": "2025-12-23T07:30:00.000000",
    "system": {
      "cpu_usage_percent": 15.5,
      "memory_usage_percent": 45.2,
      "disk_usage_percent": 32.1
    },
    "services": {
      "active_agents": 10,
      "total_executions_24h": 1250,
      "success_rate_percent": 98.5
    },
    "billing": {
      "total_eu_consumed_24h": 1250.5,
      "total_cost_24h": 12.50
    }
  },
  "stats": {
    "agents": {
      "total": 50,
      "active": 45
    },
    "executions": {
      "total_7d": 8750,
      "completed": 8600
    },
    "tools": {
      "total": 20,
      "active": 18
    },
    "users": {
      "total": 100,
      "active": 95
    }
  },
  "alerts": {
    "items": [
      {
        "severity": "warning",
        "type": "high_cpu",
        "message": "CPU使用率过高: 85.5%",
        "timestamp": "2025-12-23T07:29:00.000000"
      }
    ],
    "count": 1,
    "critical_count": 0,
    "warning_count": 1
  }
}

响应字段说明:

  • health: 系统健康状态
  • metrics: 系统性能指标
  • stats: 服务统计信息
  • alerts: 系统告警
    • items: 告警列表
    • count: 告警总数
    • critical_count: 严重告警数
    • warning_count: 警告告警数

4. 请求/响应示例

4.1 cURL 示例

获取系统性能指标

curl -X GET "http://localhost:8002/api/v1/monitoring/metrics"

获取Agent统计

curl -X GET "http://localhost:8002/api/v1/monitoring/stats?service=agents"

获取执行趋势(7天,6小时间隔)

curl -X GET "http://localhost:8002/api/v1/monitoring/trends?metric=executions&period=7d&interval=6h"

获取严重告警

curl -X GET "http://localhost:8002/api/v1/monitoring/alerts?severity=critical"

获取监控仪表板

curl -X GET "http://localhost:8002/api/v1/monitoring/dashboard"

4.2 Python 示例

import httpx
import asyncio

async def get_monitoring_data():
    base_url = "http://localhost:8002"
    
    async with httpx.AsyncClient() as client:
        # 获取系统指标
        metrics = await client.get(f"{base_url}/api/v1/monitoring/metrics")
        print("系统指标:", metrics.json())
        
        # 获取服务统计
        stats = await client.get(f"{base_url}/api/v1/monitoring/stats?service=all")
        print("服务统计:", stats.json())
        
        # 获取性能趋势
        trends = await client.get(
            f"{base_url}/api/v1/monitoring/trends",
            params={"metric": "executions", "period": "24h", "interval": "1h"}
        )
        print("性能趋势:", trends.json())
        
        # 获取告警
        alerts = await client.get(f"{base_url}/api/v1/monitoring/alerts")
        print("系统告警:", alerts.json())
        
        # 获取监控仪表板
        dashboard = await client.get(f"{base_url}/api/v1/monitoring/dashboard")
        print("监控仪表板:", dashboard.json())

asyncio.run(get_monitoring_data())

4.3 JavaScript 示例

const baseUrl = 'http://localhost:8002';

// 获取系统指标
async function getMetrics() {
  const response = await fetch(`${baseUrl}/api/v1/monitoring/metrics`);
  const data = await response.json();
  console.log('系统指标:', data);
}

// 获取服务统计
async function getStats(service = 'all') {
  const response = await fetch(`${baseUrl}/api/v1/monitoring/stats?service=${service}`);
  const data = await response.json();
  console.log('服务统计:', data);
}

// 获取性能趋势
async function getTrends(metric = 'executions', period = '24h', interval = '1h') {
  const url = new URL(`${baseUrl}/api/v1/monitoring/trends`);
  url.searchParams.append('metric', metric);
  url.searchParams.append('period', period);
  url.searchParams.append('interval', interval);
  
  const response = await fetch(url);
  const data = await response.json();
  console.log('性能趋势:', data);
}

// 获取告警
async function getAlerts(severity = null) {
  let url = `${baseUrl}/api/v1/monitoring/alerts`;
  if (severity) {
    url += `?severity=${severity}`;
  }
  
  const response = await fetch(url);
  const data = await response.json();
  console.log('系统告警:', data);
}

// 获取监控仪表板
async function getDashboard() {
  const response = await fetch(`${baseUrl}/api/v1/monitoring/dashboard`);
  const data = await response.json();
  console.log('监控仪表板:', data);
}

// 使用示例
getMetrics();
getStats('agents');
getTrends('executions', '7d', '6h');
getAlerts('critical');
getDashboard();

5. 错误处理

5.1 错误响应格式

{
  "detail": "错误描述信息"
}

5.2 常见错误

HTTP状态码 错误类型 说明
400 Bad Request 请求参数错误
500 Internal Server Error 服务器内部错误

5.3 错误处理示例

import httpx

async def get_metrics_safe():
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get("http://localhost:8002/api/v1/monitoring/metrics")
            response.raise_for_status()
            return response.json()
    except httpx.HTTPStatusError as e:
        print(f"HTTP错误: {e.response.status_code}")
        print(f"错误信息: {e.response.text}")
    except Exception as e:
        print(f"其他错误: {e}")

6. 集成示例

6.1 实时监控仪表板

import asyncio
import httpx
from datetime import datetime

async def update_dashboard():
    """每30秒更新一次监控仪表板"""
    base_url = "http://localhost:8002"
    
    while True:
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(f"{base_url}/api/v1/monitoring/dashboard")
                data = response.json()
                
                # 显示关键指标
                print(f"\n[{datetime.now()}] 监控仪表板")
                print(f"系统状态: {data['health']['status']}")
                print(f"CPU使用率: {data['metrics']['system']['cpu_usage_percent']:.1f}%")
                print(f"内存使用率: {data['metrics']['system']['memory_usage_percent']:.1f}%")
                print(f"活跃Agent: {data['metrics']['services']['active_agents']}")
                print(f"24小时执行次数: {data['metrics']['services']['total_executions_24h']}")
                print(f"成功率: {data['metrics']['services']['success_rate_percent']:.2f}%")
                print(f"告警数量: {data['alerts']['count']} (严重: {data['alerts']['critical_count']})")
                
        except Exception as e:
            print(f"获取监控数据失败: {e}")
        
        await asyncio.sleep(30)

# 运行监控
asyncio.run(update_dashboard())

6.2 告警通知

import httpx
import asyncio

async def check_alerts():
    """检查系统告警并发送通知"""
    base_url = "http://localhost:8002"
    
    async with httpx.AsyncClient() as client:
        # 获取严重告警
        response = await client.get(f"{base_url}/api/v1/monitoring/alerts?severity=critical")
        alerts = response.json()
        
        if alerts['count'] > 0:
            print(f"⚠️ 发现 {alerts['count']} 个严重告警:")
            for alert in alerts['alerts']:
                print(f"  - {alert['message']} ({alert['type']})")
                # 这里可以添加通知逻辑(邮件、短信、Slack等)
        
        # 获取警告告警
        response = await client.get(f"{base_url}/api/v1/monitoring/alerts?severity=warning")
        alerts = response.json()
        
        if alerts['count'] > 0:
            print(f"⚠️ 发现 {alerts['count']} 个警告:")
            for alert in alerts['alerts']:
                print(f"  - {alert['message']} ({alert['type']})")

asyncio.run(check_alerts())

7. 最佳实践

7.1 监控频率建议

  • 系统指标: 每30秒-1分钟查询一次
  • 服务统计: 每5-10分钟查询一次
  • 性能趋势: 根据需求,建议每1小时查询一次
  • 系统告警: 每1-5分钟检查一次

7.2 性能优化

  • 使用 /api/v1/monitoring/dashboard 端点获取聚合数据,减少请求次数
  • 对于趋势数据,合理选择时间范围和间隔,避免查询过大数据集
  • 使用缓存机制,避免频繁查询数据库

7.3 告警阈值建议

  • CPU使用率: > 80% 警告,> 90% 严重
  • 内存使用率: > 85% 警告,> 95% 严重
  • 磁盘使用率: > 85% 警告,> 90% 严重
  • 失败率: > 5% 警告,> 10% 严重

8. 更新日志

v2.0 (2025-12-23)

  • ✅ 新增系统性能指标API
  • ✅ 新增服务统计信息API
  • ✅ 新增性能趋势数据API
  • ✅ 新增系统告警API
  • ✅ 新增监控仪表板API
  • ✅ 优化健康检查API

文档版本: v2.0
最后更新: 2025年12月23日
维护者: taiji-AI-PAD 开发团队