Skip to main content

Agent Intelligence Advanced

Capabilities

Agent Intelligence Advanced

EnerOS v0.43.0 significantly enhances Agent intelligence, integrating LLM (via rig framework), reasoning engine, feedback learning loop, anomaly detection, and predictive maintenance capabilities. Agents are no longer just rule executors, but intelligent entities with understanding, reasoning, and learning capabilities. The intelligence advancement is provided by the eneros-agent, eneros-reasoning, and eneros-tool crates working together.

Intelligent Agent Architecture

┌──────────────────────────────────────────────────────────────┐
│                     Agent Intelligence Layer                  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
│  │ LLM      │  │ Reasoning│  │ Feedback │  │ RAG      │    │
│  │ Integration│  │ Engine   │  │ Learning │  │ Retrieval│    │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘    │
│       │             │             │             │            │
│       └─────────────┴─────────────┴─────────────┘            │
│                           │                                  │
└───────────────────────────┼──────────────────────────────────┘

┌───────────────────────────▼──────────────────────────────────┐
│                     Perception and Execution Layer            │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
│  │ Anomaly  │  │ Predictive│  │ Tool     │  │ Decision │    │
│  │ Detection│  │ Maintenance│  │ Invocation│  │ Execution│   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘    │
└──────────────────────────────────────────────────────────────┘
CapabilityImplementing CrateKey Technology
LLM Integrationeneros-agentrig framework + multi-Provider
Reasoning Engineeneros-reasoningReAct / CoT / ToT / Reflexion
Feedback Learningeneros-agentRLHF + Policy Gradient
Anomaly Detectioneneros-agentIsolation Forest + Change Point Detection
Predictive Maintenanceeneros-agentLSTM + Transformer
RAG Retrievaleneros-agentVector Database + Embedding

LLM Integration

Unified access to multiple LLM backends via the rig framework, supporting streaming output, function calling, and multimodal:

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)                    // Low temperature for determinism
    .system_prompt("You are a power dispatch assistant, providing suggestions based on grid status.")
    .retry(RetryPolicy::exponential(3))
    .build().await?;

// Streaming call
let response = llm.chat()
    .user(format!(
        "Current load {:.1} MW, forecast deviation 3.2%, frequency {:.2} Hz, please analyze.",
        load, frequency
    ))
    .stream(|chunk| async move {
        print!("{}", chunk.delta);
        Ok(())
    })
    .await?;

println!("\nLLM suggestion: {}", response.content);
println!("Token usage: input {} / output {}", response.usage.input, response.usage.output);

Function Calling

LLM can invoke the EnerOS built-in toolset:

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

let tools = vec![
    Tool::new("get_bus_voltage", "Query bus voltage", ToolSchema {
        parameters: json!({
            "bus_id": { "type": "string", "description": "Bus 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", "Execute load flow calculation", ToolSchema {
        parameters: json!({
            "network": { "type": "string", "description": "Grid name" }
        }),
    }, |args| async {
        let result = powerflow.solve(&network).await?;
        Ok(serde_json::to_value(&result)?)
    }),
];

let response = llm.chat()
    .user("Check bus 5 voltage, adjust reactive compensation if necessary")
    .tools(tools)
    .send().await?;

Multi-Backend Support

ProviderModelApplicableLocal
OpenAIGPT-4o / o1-previewGeneral reasoning
AnthropicClaude 3.5 SonnetLong context
AzureAzure OpenAIEnterprise compliance
LocalLlama 3.1 70BData sensitive
LocalQwen2 72BChinese scenarios
QwenQwen-MaxDomestic compliance
ERNIEERNIE 4.0Domestic compliance

LLM Configuration Parameters

ParameterDefaultDescription
providerOpenAILLM service provider
modelgpt-4oModel name
temperature0.3Temperature (low for power scenarios)
max_tokens2048Maximum output tokens
timeout30sRequest timeout
retry3 timesExponential backoff retry
streamfalseWhether streaming output
cache_ttl1hResponse cache duration

Reasoning Engine

Structured reasoning engine supports ReAct, Chain-of-Thought, Tree-of-Thought and other modes, converting LLM output into executable action sequences:

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);  // Reflect every 3 steps

let plan = reasoner
    .think("Grid frequency is low (49.95Hz), needs to recover to 50Hz within 5 minutes")
    .await?;

// plan is an ordered action sequence
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?;
        }
    }
}

Reasoning Strategy Comparison

StrategyApplicableLatencyAccuracyToken Usage
ReActTool-call intensive1-5s88%Medium
CoTSingle-step reasoning0.5-2s82%Low
ToTMulti-branch decisions5-30s93%High
ReflexionSelf-correction10-60s91%High
Plan-and-ExecuteLong-horizon tasks10-30s90%Medium

Reflexion Self-Correction

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);

// Automatically reflect and retry on reasoning failure
let plan = reasoner.think("Complex fault recovery scenario").await?;
println!("Number of trials: {}", plan.trials);

Feedback Learning

After executing decisions, Agents collect result feedback to continuously optimize policies:

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

let mut feedback_loop = FeedbackLoop::new()
    .reward(Reward::composite(vec![
        Reward::grid_stability(0.5),       // Grid stability weight 0.5
        Reward::economic_efficiency(0.3),  // Economic efficiency weight 0.3
        Reward::safety_compliance(0.2),    // Safety compliance weight 0.2
    ]))
    .window(1000)                          // Sliding window
    .policy(Policy::ppo()                  // PPO policy gradient
        .learning_rate(0.001)
        .batch_size(64)
        .clip_ratio(0.2))
    .update_interval(Duration::from_secs(3600));  // Update every hour

// Submit feedback after executing decision
feedback_loop.observe(state_before, action, state_after).await?;

// Policy update
feedback_loop.update_policy().await?;

// Evaluate improvement
let improvement = feedback_loop.evaluate().await?;
println!("Policy improvement: {:.2}%", improvement * 100.0);
println!("Average reward: {:.4}", feedback_loop.avg_reward().await?);

Reward Function

Reward ItemCalculationWeight
Grid stabilityInverse of frequency/voltage deviation0.5
Economic efficiencyInverse of generation cost0.3
Safety complianceConstraint violation penalty0.2
Response speedInverse of decision latencyOptional

Anomaly Detection

Automatically detects grid anomalies based on time-series data, supporting multiple algorithms:

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!("Anomaly: type={:?} score={:.2} bus={}",
        anomaly.anomaly_type, anomaly.score, anomaly.location);
    ctx.dispatch(EmergencyAgent::handle(anomaly)).await?;
}

Anomaly Types

TypeDetection MethodResponse Action
Voltage limit violationStatistical + rulesAutomatic voltage regulation
Load sudden changeChange point detectionReserve capacity activation
OscillationSpectrum analysis (FFT)PSS adjustment
Equipment degradationTrend analysisMaintenance work order
Cyber attackBehavior baselineSecurity isolation
Harmonic exceedanceHarmonic analysisFilter activation

Predictive Maintenance

Predicts faults based on equipment historical data, covering transformers, circuit breakers, cables, and other key equipment:

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-day time-series input
    .features(vec!["temperature", "vibration", "partial_discharge", "load"])
    .horizon(Duration::from_secs(86400 * 30));  // 30-day prediction

let health = pm.predict(transformer_id).await?;
println!("Health score: {:.1}%", health.score * 100.0);
println!("Estimated remaining life: {} days", health.remaining_life_days);
println!("Confidence interval: [{}, {}] days",
    health.rUL_lower, health.rUL_upper);

if health.score < 0.7 {
    // Automatically generate maintenance work order
    let work_order = MaintenanceAgent::schedule(transformer_id)
        .priority(health.score_to_priority())
        .recommended_action(&health.recommendation)
        .await?;
    println!("Work order created: {}", work_order.id);
}

Equipment Health Level

Health ScoreLevelAction
> 0.9ExcellentNormal operation
0.8-0.9GoodEnhanced monitoring
0.7-0.8MediumScheduled maintenance
0.5-0.7PoorEmergency maintenance
< 0.5CriticalImmediate shutdown

RAG Knowledge Base

Agents can retrieve power domain knowledge bases (regulations, standards, cases) and inject retrieval results into LLM context:

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())   // Chinese Embedding
    .vector_store(VectorStore::faiss()
        .dimension(1024)
        .index_type(IndexType::IVF))
    .retriever(Retriever::hybrid()           // Hybrid retrieval
        .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 meter communication protocol security requirements").await?;
for doc in &context.documents {
    println!("[score={:.2}] {}", doc.score, doc.title);
}

// Inject retrieval results into LLM prompt
let response = llm.chat()
    .system("You are a power regulation expert. Answer questions based on the following retrieval results.")
    .context(&context.to_prompt())
    .user("What are the security levels of the DL/T 698.45 protocol?")
    .send().await?;

Knowledge Base Configuration Parameters

ParameterDefaultDescription
embeddingbge-large-zhEmbedding model
vector_storeFAISSVector database
top_k5Retrieval count
reranktrueRe-ranking
chunk_size512Chunk size
chunk_overlap50Chunk overlap
min_score0.6Minimum similarity threshold

Performance Metrics

OperationLatencyRemarks
LLM single call0.5-30sDepends on model and tokens
ReAct reasoning (5 steps)5-15sIncluding tool calls
Anomaly detection< 100msSingle inference
Predictive maintenance inference< 200msLSTM single forward pass
RAG retrieval (10k documents)< 50msIncluding re-ranking
Policy update< 1sPPO one gradient
Embedding generation< 20msSingle document
Function call execution< 1sDepends on tool

Relationship with Other Capabilities

  • Multi-Agent Collaboration: Agent collaboration framework depends on reasoning engine, see Multi-Agent Collaboration
  • Grid Analysis Advanced: Analysis capabilities support reasoning decisions, see Grid Analysis Advanced
  • Digital Twin Engine: What-If validates reasoning results, see Digital Twin Engine
  • Safety Guard: Intelligent decisions must pass safety gateway validation, see Safety Guard
  • High Availability: AIOps alert clustering uses reasoning capabilities