跳到主内容

Agent智能进阶

核心能力

Agent 智能进阶

EnerOS v0.43.0 大幅提升 Agent 智能水平,集成 LLM(通过 rig 框架)、推理引擎、反馈学习循环、异常检测与预测性维护能力。Agent 不再只是规则执行器,而是具备理解、推理、学习能力的智能体。智能进阶由 eneros-agenteneros-reasoningeneros-tool 三个 crate 协同提供。

智能体架构

┌──────────────────────────────────────────────────────────────┐
│                     Agent 智能层                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
│  │ LLM 集成 │  │ 推理引擎 │  │ 反馈学习 │  │ RAG 检索 │    │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘    │
│       │             │             │             │            │
│       └─────────────┴─────────────┴─────────────┘            │
│                           │                                  │
└───────────────────────────┼──────────────────────────────────┘

┌───────────────────────────▼──────────────────────────────────┐
│                     感知与执行层                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
│  │ 异常检测 │  │ 预测维护 │  │ 工具调用 │  │ 决策执行 │    │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘    │
└──────────────────────────────────────────────────────────────┘
能力实现 crate关键技术
LLM 集成eneros-agentrig 框架 + 多 Provider
推理引擎eneros-reasoningReAct / CoT / ToT / Reflexion
反馈学习eneros-agentRLHF + 策略梯度
异常检测eneros-agentIsolation Forest + 变点检测
预测维护eneros-agentLSTM + Transformer
RAG 检索eneros-agent向量数据库 + Embedding

LLM 集成

通过 rig 框架统一接入多种 LLM 后端,支持流式输出、函数调用、多模态:

use eneros_agent::llm::{LlmClient, Provider, Model, StreamCallback};
use std::time::Duration;

let llm = LlmClient::builder()
    .provider(Provider::OpenAI)
    .model(Model::gpt_4o())
    .api_key_from_env()
    .timeout(Duration::from_secs(30))
    .max_tokens(2048)
    .temperature(0.3)                    // 低温度保证确定性
    .system_prompt("你是电力调度助手,根据电网状态给出建议。")
    .retry(RetryPolicy::exponential(3))
    .build().await?;

// 流式调用
let response = llm.chat()
    .user(format!(
        "当前负荷 {:.1} MW,预测偏差 3.2%,频率 {:.2} Hz,请分析。",
        load, frequency
    ))
    .stream(|chunk| async move {
        print!("{}", chunk.delta);
        Ok(())
    })
    .await?;

println!("\nLLM 建议: {}", response.content);
println!("Token 用量: 输入 {} / 输出 {}", response.usage.input, response.usage.output);

函数调用

LLM 可调用 EnerOS 内置工具集:

use eneros_agent::llm::{Tool, ToolSchema};

let tools = vec![
    Tool::new("get_bus_voltage", "查询母线电压", ToolSchema {
        parameters: json!({
            "bus_id": { "type": "string", "description": "母线 ID" }
        }),
    }, |args| async {
        let bus_id = args["bus_id"].as_str().unwrap();
        let v = kernel.get_bus_voltage(bus_id).await?;
        Ok(json!({ "voltage": v }))
    }),
    Tool::new("run_powerflow", "执行潮流计算", ToolSchema {
        parameters: json!({
            "network": { "type": "string", "description": "电网名称" }
        }),
    }, |args| async {
        let result = powerflow.solve(&network).await?;
        Ok(serde_json::to_value(&result)?)
    }),
];

let response = llm.chat()
    .user("检查 5 号母线电压,必要时调整无功补偿")
    .tools(tools)
    .send().await?;

多后端支持

Provider模型适用是否本地
OpenAIGPT-4o / o1-preview通用推理
AnthropicClaude 3.5 Sonnet长上下文
AzureAzure OpenAI企业合规
本地Llama 3.1 70B数据敏感
本地Qwen2 72B中文场景
通义千问Qwen-Max国内合规
文心一言ERNIE 4.0国内合规

LLM 配置参数

参数默认值说明
providerOpenAILLM 服务商
modelgpt-4o模型名称
temperature0.3温度(电力场景偏低)
max_tokens2048最大输出 token
timeout30s请求超时
retry3 次指数退避重试
streamfalse是否流式输出
cache_ttl1h响应缓存时长

推理引擎

结构化推理引擎支持 ReAct、Chain-of-Thought、Tree-of-Thought 等模式,将 LLM 输出转化为可执行的动作序列:

use eneros_agent::reasoning::{Reasoner, Strategy, Action};

let reasoner = Reasoner::new()
    .strategy(Strategy::react())
    .llm(llm)
    .tools(ctx.tools())
    .max_steps(10)
    .max_tokens_per_step(512)
    .reflection_interval(3);  // 每 3 步反思一次

let plan = reasoner
    .think("电网频率偏低(49.95Hz),需在 5 分钟内恢复至 50Hz")
    .await?;

// plan 是一个有序的动作序列
for action in &plan.actions {
    match action {
        Action::IncreaseGen { gen_id, mw } => {
            kernel.dispatch(gen_id, *mw).await?;
        }
        Action::ShedLoad { feeder_id, mw } => {
            kernel.shed_load(feeder_id, *mw).await?;
        }
        Action::AdjustVoltage { bus_id, target } => {
            kernel.adjust_voltage(bus_id, *target).await?;
        }
        Action::Notify { channel, msg } => {
            notify(channel, msg).await?;
        }
    }
}

推理策略对比

策略适用时延准确率Token 用量
ReAct工具调用密集1-5s88%
CoT单步推理0.5-2s82%
ToT多分支决策5-30s93%
Reflexion自我修正10-60s91%
Plan-and-Execute长程任务10-30s90%

Reflexion 自我修正

use eneros_agent::reasoning::ReflexionConfig;

let reasoner = Reasoner::new()
    .strategy(Strategy::reflexion(ReflexionConfig {
        max_trials: 3,
        evaluation: Evaluation::grid_stability(),
        memory_size: 5,
    }))
    .llm(llm);

// 推理失败时自动反思并重试
let plan = reasoner.think("复杂故障恢复场景").await?;
println!("尝试次数: {}", plan.trials);

反馈学习

Agent 执行决策后,收集结果反馈,持续优化策略:

use eneros_agent::learning::{FeedbackLoop, Reward, Policy};

let mut feedback_loop = FeedbackLoop::new()
    .reward(Reward::composite(vec![
        Reward::grid_stability(0.5),       // 电网稳定度权重 0.5
        Reward::economic_efficiency(0.3),  // 经济效率权重 0.3
        Reward::safety_compliance(0.2),    // 安全合规权重 0.2
    ]))
    .window(1000)                          // 滑动窗口
    .policy(Policy::ppo()                  // PPO 策略梯度
        .learning_rate(0.001)
        .batch_size(64)
        .clip_ratio(0.2))
    .update_interval(Duration::from_secs(3600));  // 每小时更新

// 执行决策后提交反馈
feedback_loop.observe(state_before, action, state_after).await?;

// 策略更新
feedback_loop.update_policy().await?;

// 评估改进效果
let improvement = feedback_loop.evaluate().await?;
println!("策略改进: {:.2}%", improvement * 100.0);
println!("平均奖励: {:.4}", feedback_loop.avg_reward().await?);

奖励函数

奖励项计算方式权重
电网稳定度频率/电压偏差倒数0.5
经济效率发电成本倒数0.3
安全合规约束违反惩罚0.2
响应速度决策时延倒数可选

异常检测

基于时序数据自动检测电网异常,支持多种算法:

use eneros_agent::anomaly::{AnomalyDetector, Algorithm, FeatureSet};

let detector = AnomalyDetector::new()
    .algorithm(Algorithm::isolation_forest()
        .n_trees(100)
        .sample_size(256))
    .features(FeatureSet::new()
        .add("voltage", Window::last(Duration::from_secs(3600)))
        .add("frequency", Window::last(Duration::from_secs(3600)))
        .add("load", Window::last(Duration::from_secs(3600))))
    .window(Duration::from_secs(3600))
    .threshold(0.95)
    .min_samples(1000)
    .retrain_interval(Duration::from_secs(86400));

detector.start().await?;

while let Some(anomaly) = detector.alerts().recv().await {
    println!("异常: type={:?} score={:.2} bus={}",
        anomaly.anomaly_type, anomaly.score, anomaly.location);
    ctx.dispatch(EmergencyAgent::handle(anomaly)).await?;
}

异常类型

类型检测方法响应动作
电压越限统计 + 规则自动调压
负荷突变变点检测备用容量投入
振荡频谱分析(FFT)PSS 调整
设备退化趋势分析检修工单
网络攻击行为基线安全隔离
谐波超标谐波分析滤波器投入

预测性维护

基于设备历史数据预测故障,覆盖变压器、断路器、电缆等关键设备:

use eneros_agent::maintenance::{PredictiveMaintenance, HealthScore, Model};

let pm = PredictiveMaintenance::new()
    .model(Model::lstm()
        .hidden_size(128)
        .num_layers(2)
        .sequence_length(24 * 7))   // 7 天时序输入
    .features(vec!["temperature", "vibration", "partial_discharge", "load"])
    .horizon(Duration::from_secs(86400 * 30));  // 30 天预测

let health = pm.predict(transformer_id).await?;
println!("健康度: {:.1}%", health.score * 100.0);
println!("预计剩余寿命: {} 天", health.remaining_life_days);
println!("置信区间: [{}, {}] 天",
    health.rUL_lower, health.rUL_upper);

if health.score < 0.7 {
    // 自动生成检修工单
    let work_order = MaintenanceAgent::schedule(transformer_id)
        .priority(health.score_to_priority())
        .recommended_action(&health.recommendation)
        .await?;
    println!("已创建工单: {}", work_order.id);
}

设备健康度等级

健康度等级动作
> 0.9正常运行
0.8-0.9加强监测
0.7-0.8计划检修
0.5-0.7紧急检修
< 0.5危险立即停运

RAG 知识库

Agent 可检索电力领域知识库(规程、标准、案例),将检索结果注入 LLM 上下文:

use eneros_agent::rag::{RagEngine, KnowledgeBase, Embedding, Retriever};

let rag = RagEngine::new()
    .knowledge_base(KnowledgeBase::load("/data/grid-codes")
        .add_dir("/data/standards/iec")
        .add_dir("/data/standards/dl")
        .add_dir("/data/cases"))
    .embedding(Embedding::bge_large_zh())   // 中文 Embedding
    .vector_store(VectorStore::faiss()
        .dimension(1024)
        .index_type(IndexType::IVF))
    .retriever(Retriever::hybrid()           // 混合检索
        .semantic_weight(0.7)
        .keyword_weight(0.3))
    .top_k(5)
    .rerank(true)
    .chunk_size(512)
    .chunk_overlap(50);

let context = rag.retrieve("DL/T 698.45 电能表通信协议安全要求").await?;
for doc in &context.documents {
    println!("[score={:.2}] {}", doc.score, doc.title);
}

// 将检索结果注入 LLM prompt
let response = llm.chat()
    .system("你是电力规程专家。基于以下检索结果回答问题。")
    .context(&context.to_prompt())
    .user("DL/T 698.45 协议的安全等级有哪些?")
    .send().await?;

知识库配置参数

参数默认值说明
embeddingbge-large-zh嵌入模型
vector_storeFAISS向量数据库
top_k5检索条数
reranktrue重排序
chunk_size512分块大小
chunk_overlap50分块重叠
min_score0.6最小相似度阈值

性能指标

操作延迟备注
LLM 单次调用0.5-30s取决于模型与 token
ReAct 推理(5 步)5-15s含工具调用
异常检测< 100ms单次推理
预测性维护推理< 200msLSTM 单次前向
RAG 检索(10k 文档)< 50ms含重排序
策略更新< 1sPPO 一次梯度
Embedding 生成< 20ms单文档
函数调用执行< 1s取决于工具

与其他能力的关系

  • 多智能体协作:智能体协作框架依赖推理引擎,详见 多智能体协作
  • 电网分析进阶:分析能力支撑推理决策,详见 电网分析进阶
  • 数字孪生引擎:What-If 验证推理结果,详见 数字孪生引擎
  • 安全守卫:智能决策需通过安全网关校验,详见 安全守卫
  • 高可用:AIOps 告警聚类使用推理能力

相关文档