Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

监控与可观测性

监控仪表盘和可观测性功能示例。

Web 监控仪表盘

实时 Web 仪表盘用于智能体监控。

位置: examples/monitoring_dashboard/

use mofa_sdk::dashboard::{DashboardConfig, DashboardServer, MetricsCollector};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // 配置仪表盘
    let config = DashboardConfig::new()
        .with_host("127.0.0.1")
        .with_port(8080)
        .with_cors(true)
        .with_ws_interval(Duration::from_secs(1));

    // 创建仪表盘服务器
    let mut server = DashboardServer::new(config);

    // 获取指标收集器
    let collector = server.collector();

    // 启动演示数据生成器(实际应用中使用真实智能体指标)
    tokio::spawn(async move {
        generate_demo_data(collector).await;
    });

    // 构建路由并启动服务器
    let router = server.build_router();
    let addr: SocketAddr = "127.0.0.1:8080".parse()?;
    let listener = tokio::net::TcpListener::bind(addr).await?;

    println!("仪表盘运行在 http://{}", addr);
    axum::serve(listener, router).await?;

    Ok(())
}

更新指标

向仪表盘推送指标:

#![allow(unused)]
fn main() {
use mofa_sdk::dashboard::{AgentMetrics, WorkflowMetrics, PluginMetrics};

// 更新智能体指标
let agent_metrics = AgentMetrics {
    agent_id: "agent-001".to_string(),
    name: "研究智能体".to_string(),
    state: "running".to_string(),
    tasks_completed: 42,
    tasks_failed: 2,
    tasks_in_progress: 3,
    messages_sent: 150,
    messages_received: 148,
    last_activity: now(),
    avg_task_duration_ms: 250.0,
};

collector.update_agent(agent_metrics).await;

// 更新工作流指标
let workflow_metrics = WorkflowMetrics {
    workflow_id: "wf-001".to_string(),
    name: "内容流水线".to_string(),
    status: "running".to_string(),
    total_executions: 100,
    successful_executions: 95,
    failed_executions: 5,
    running_instances: 2,
    avg_execution_time_ms: 5000.0,
    node_count: 5,
};

collector.update_workflow(workflow_metrics).await;

// 更新插件指标
let plugin_metrics = PluginMetrics {
    plugin_id: "plugin-001".to_string(),
    name: "OpenAI LLM".to_string(),
    version: "1.0.0".to_string(),
    state: "running".to_string(),
    call_count: 1000,
    error_count: 5,
    avg_response_time_ms: 150.0,
    last_reload: Some(now()),
    reload_count: 3,
};

collector.update_plugin(plugin_metrics).await;
}

WebSocket 实时更新

仪表盘提供 WebSocket 用于实时更新:

#![allow(unused)]
fn main() {
// 获取 WebSocket 处理器
if let Some(ws_handler) = server.ws_handler() {
    let ws = ws_handler.clone();
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(Duration::from_secs(30));
        loop {
            interval.tick().await;
            ws.send_alert(
                "info",
                "系统运行正常",
                "health-check",
            ).await;
        }
    });
}
}

API 端点

仪表盘暴露 REST API 端点:

端点描述
GET /api/overview仪表盘概览
GET /api/metrics当前指标快照
GET /api/agents列出所有智能体
GET /api/agents/:id获取智能体详情
GET /api/workflows列出所有工作流
GET /api/plugins列出所有插件
GET /api/system系统状态
GET /api/health健康检查

访问仪表盘

# 启动仪表盘
cargo run -p monitoring_dashboard

# 在浏览器中打开
open http://127.0.0.1:8080

# WebSocket 端点
ws://127.0.0.1:8080/ws

# API 基础 URL
http://127.0.0.1:8080/api

与智能体集成

将智能体连接到仪表盘:

#![allow(unused)]
fn main() {
use mofa_sdk::monitoring::MetricsEmitter;

// 创建连接到仪表盘的发射器
let emitter = MetricsEmitter::new("http://127.0.0.1:8080/api");

// 在智能体执行中
async fn execute(&mut self, input: AgentInput, ctx: &AgentContext) -> AgentResult<AgentOutput> {
    let start = Instant::now();

    // ... 执行工作 ...

    // 发送指标
    emitter.emit_task_completed(
        self.id(),
        start.elapsed().as_millis() as f64,
    ).await;

    Ok(output)
}
}

运行示例

# 启动监控仪表盘
cargo run -p monitoring_dashboard

# 访问 http://127.0.0.1:8080

可用示例

示例描述
monitoring_dashboardWeb 监控仪表盘

相关链接