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│ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└──────────────────────────────────────────────────────────────┘
| Capability | Implementing Crate | Key Technology |
|---|
| LLM Integration | eneros-agent | rig framework + multi-Provider |
| Reasoning Engine | eneros-reasoning | ReAct / CoT / ToT / Reflexion |
| Feedback Learning | eneros-agent | RLHF + Policy Gradient |
| Anomaly Detection | eneros-agent | Isolation Forest + Change Point Detection |
| Predictive Maintenance | eneros-agent | LSTM + Transformer |
| RAG Retrieval | eneros-agent | Vector 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
| Provider | Model | Applicable | Local |
|---|
| OpenAI | GPT-4o / o1-preview | General reasoning | ❌ |
| Anthropic | Claude 3.5 Sonnet | Long context | ❌ |
| Azure | Azure OpenAI | Enterprise compliance | ❌ |
| Local | Llama 3.1 70B | Data sensitive | ✅ |
| Local | Qwen2 72B | Chinese scenarios | ✅ |
| Qwen | Qwen-Max | Domestic compliance | ❌ |
| ERNIE | ERNIE 4.0 | Domestic compliance | ❌ |
LLM Configuration Parameters
| Parameter | Default | Description |
|---|
| provider | OpenAI | LLM service provider |
| model | gpt-4o | Model name |
| temperature | 0.3 | Temperature (low for power scenarios) |
| max_tokens | 2048 | Maximum output tokens |
| timeout | 30s | Request timeout |
| retry | 3 times | Exponential backoff retry |
| stream | false | Whether streaming output |
| cache_ttl | 1h | Response 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
| Strategy | Applicable | Latency | Accuracy | Token Usage |
|---|
| ReAct | Tool-call intensive | 1-5s | 88% | Medium |
| CoT | Single-step reasoning | 0.5-2s | 82% | Low |
| ToT | Multi-branch decisions | 5-30s | 93% | High |
| Reflexion | Self-correction | 10-60s | 91% | High |
| Plan-and-Execute | Long-horizon tasks | 10-30s | 90% | 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 Item | Calculation | Weight |
|---|
| Grid stability | Inverse of frequency/voltage deviation | 0.5 |
| Economic efficiency | Inverse of generation cost | 0.3 |
| Safety compliance | Constraint violation penalty | 0.2 |
| Response speed | Inverse of decision latency | Optional |
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
| Type | Detection Method | Response Action |
|---|
| Voltage limit violation | Statistical + rules | Automatic voltage regulation |
| Load sudden change | Change point detection | Reserve capacity activation |
| Oscillation | Spectrum analysis (FFT) | PSS adjustment |
| Equipment degradation | Trend analysis | Maintenance work order |
| Cyber attack | Behavior baseline | Security isolation |
| Harmonic exceedance | Harmonic analysis | Filter 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 Score | Level | Action |
|---|
| > 0.9 | Excellent | Normal operation |
| 0.8-0.9 | Good | Enhanced monitoring |
| 0.7-0.8 | Medium | Scheduled maintenance |
| 0.5-0.7 | Poor | Emergency maintenance |
| < 0.5 | Critical | Immediate 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
| Parameter | Default | Description |
|---|
| embedding | bge-large-zh | Embedding model |
| vector_store | FAISS | Vector database |
| top_k | 5 | Retrieval count |
| rerank | true | Re-ranking |
| chunk_size | 512 | Chunk size |
| chunk_overlap | 50 | Chunk overlap |
| min_score | 0.6 | Minimum similarity threshold |
| Operation | Latency | Remarks |
|---|
| LLM single call | 0.5-30s | Depends on model and tokens |
| ReAct reasoning (5 steps) | 5-15s | Including tool calls |
| Anomaly detection | < 100ms | Single inference |
| Predictive maintenance inference | < 200ms | LSTM single forward pass |
| RAG retrieval (10k documents) | < 50ms | Including re-ranking |
| Policy update | < 1s | PPO one gradient |
| Embedding generation | < 20ms | Single document |
| Function call execution | < 1s | Depends 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