-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathenhanced_atomic_server_example.rs
More file actions
292 lines (247 loc) · 11.1 KB
/
Copy pathenhanced_atomic_server_example.rs
File metadata and controls
292 lines (247 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Enhanced Atomic Server Configuration with Multi-Agent System
//!
//! This example demonstrates how the new multi-agent system works with
//! atomic server configurations, showing the evolution from simple Role
//! configurations to intelligent autonomous agents.
use ahash::AHashMap;
use terraphim_config::{ConfigBuilder, Haystack, Role, ServiceType};
use terraphim_multi_agent::{
CommandInput, CommandType, MultiAgentError, MultiAgentResult, TerraphimAgent,
};
use terraphim_persistence::DeviceStorage;
use terraphim_types::RelevanceFunction;
/// Create an atomic server role that becomes a multi-agent
fn create_atomic_server_agent_role() -> Role {
Role {
terraphim_it: true,
shortname: Some("AtomicAgent".to_string()),
name: "AtomicServerAgent".into(),
relevance_function: RelevanceFunction::TitleScorer,
theme: "spacelab".to_string(),
kg: None,
llm_enabled: false,
llm_api_key: None,
llm_model: None,
llm_auto_summarize: false,
llm_chat_enabled: false,
llm_chat_system_prompt: None,
llm_chat_model: None,
llm_context_window: Some(16000),
llm_router_enabled: false,
llm_router_config: None,
haystacks: vec![Haystack::new(
"http://localhost:9883".to_string(), // Atomic server URL
ServiceType::Atomic,
true, // read-only
)
.with_atomic_secret(Some("your-base64-secret-here".to_string()))],
extra: {
let mut extra = AHashMap::new();
// Multi-agent specific configuration
extra.insert(
"agent_type".to_string(),
serde_json::json!("atomic_server_specialist"),
);
extra.insert(
"capabilities".to_string(),
serde_json::json!([
"atomic_data_search",
"knowledge_retrieval",
"semantic_analysis"
]),
);
extra.insert(
"goals".to_string(),
serde_json::json!([
"Access atomic data efficiently",
"Provide semantic search",
"Maintain data consistency"
]),
);
// LLM configuration
extra.insert("llm_provider".to_string(), serde_json::json!("ollama"));
extra.insert("ollama_model".to_string(), serde_json::json!("gemma3:270m"));
extra.insert("llm_temperature".to_string(), serde_json::json!(0.4)); // Balanced for data retrieval
// Context enrichment settings
extra.insert("context_enrichment".to_string(), serde_json::json!(true));
extra.insert("max_context_tokens".to_string(), serde_json::json!(16000));
extra
},
}
}
/// Demonstrate atomic server configuration evolution
async fn demonstrate_config_evolution() -> MultiAgentResult<()> {
println!("📋 Configuration Evolution: From Role to Intelligent Agent");
println!("=========================================================");
// Step 1: Traditional configuration
println!("\n1️⃣ Step 1: Traditional Role Configuration");
let _config = ConfigBuilder::new()
.global_shortcut("Ctrl+T")
.add_role("AtomicUser", create_atomic_server_agent_role())
.build()
.expect("Failed to build config");
println!("✅ Traditional config created:");
println!(" - Role: AtomicServerAgent");
println!(" - Haystack: Atomic server (http://localhost:9883)");
println!(" - Authentication: Base64 secret");
println!(" - Read-only: true");
// Step 2: Multi-agent evolution
println!("\n2️⃣ Step 2: Multi-Agent System Evolution");
// Initialize storage
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| MultiAgentError::PersistenceError(e.to_string()))?;
// Transform role into intelligent agent
let role = create_atomic_server_agent_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
println!("✅ Role evolved into intelligent agent:");
println!(" - Agent ID: {}", agent.agent_id);
println!(" - Status: {:?}", agent.status);
println!(" - Capabilities: {:?}", agent.get_capabilities());
println!(" - Goals: {:?}", agent.goals.individual_goals);
Ok(())
}
/// Demonstrate intelligent atomic data queries
async fn demonstrate_intelligent_queries() -> MultiAgentResult<()> {
println!("\n🧠 Intelligent Atomic Data Queries");
println!("==================================");
// Initialize agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_atomic_server_agent_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Intelligent queries that leverage both atomic data and AI reasoning
let queries = vec![
(
CommandType::Answer,
"Find all resources related to data modeling in the atomic server",
),
(
CommandType::Analyze,
"Analyze the relationships between atomic data properties",
),
(
CommandType::Generate,
"Generate a summary of atomic server best practices",
),
(
CommandType::Review,
"Review the data consistency in our atomic server",
),
];
for (command_type, query_text) in queries {
println!("\n🔍 Query Type: {:?}", command_type);
println!(" Query: {}", query_text);
let input = CommandInput::new(query_text.to_string(), command_type);
let output = agent.process_command(input).await?;
println!(" 🤖 AI Response: {}", output.text);
// Show tracking information
let token_tracker = agent.token_tracker.read().await;
let cost_tracker = agent.cost_tracker.read().await;
println!(
" 📊 Tokens: {} in / {} out",
token_tracker.total_input_tokens, token_tracker.total_output_tokens
);
println!(" 💰 Cost: ${:.6}", cost_tracker.current_month_spending);
}
Ok(())
}
/// Demonstrate multi-layered context with atomic data
async fn demonstrate_context_integration() -> MultiAgentResult<()> {
println!("\n🏗️ Multi-layered Context Integration");
println!("===================================");
// Initialize agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_atomic_server_agent_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Query that should trigger comprehensive context assembly
let complex_query = "How can I optimize atomic data queries for better performance while maintaining consistency?";
println!("🎯 Complex Query: {}", complex_query);
println!("\n🔍 Context Sources Being Integrated:");
println!(" 1. 🌐 Atomic Server Data (via haystack)");
println!(" 2. 🧠 Knowledge Graph (semantic relationships)");
println!(" 3. 💭 Agent Memory (previous interactions)");
println!(" 4. 🎯 Role Goals (optimization & consistency)");
println!(" 5. ⚙️ Agent Capabilities (atomic_data_search, semantic_analysis)");
let input = CommandInput::new(complex_query.to_string(), CommandType::Analyze);
let output = agent.process_command(input).await?;
println!("\n📝 Comprehensive Analysis:");
println!("{}", output.text);
// Show context utilization
let context = agent.context.read().await;
println!("\n📊 Context Utilization:");
println!(" Context Items: {}", context.items.len());
println!(" Context Tokens: {}", context.current_tokens);
println!(
" Token Efficiency: {:.1}%",
(context.current_tokens as f32 / context.max_tokens as f32) * 100.0
);
Ok(())
}
/// Compare traditional vs intelligent approach
async fn demonstrate_evolution_comparison() -> MultiAgentResult<()> {
println!("\n⚖️ Evolution Comparison: Traditional vs Intelligent");
println!("=================================================");
println!("🔴 Traditional Approach:");
println!(" • Static role configuration");
println!(" • Manual query construction");
println!(" • Basic haystack search");
println!(" • No learning or adaptation");
println!(" • Limited context awareness");
println!("\n🟢 Multi-Agent Intelligence:");
println!(" • Dynamic agent evolution");
println!(" • AI-powered query understanding");
println!(" • Context-enriched search");
println!(" • Continuous learning from interactions");
println!(" • Semantic relationship discovery");
println!(" • Goal-aligned responses");
println!(" • Cost and performance tracking");
// Initialize intelligent agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_atomic_server_agent_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Demonstrate intelligent capabilities
let test_query = "atomic data consistency";
let input = CommandInput::new(test_query.to_string(), CommandType::Generate);
let output = agent.process_command(input).await?;
println!("\n🧪 Example: '{}'", test_query);
println!("🤖 Intelligent Response: {}", output.text);
// Show intelligence metrics
let command_history = agent.command_history.read().await;
println!("\n📈 Intelligence Metrics:");
println!(" Commands Processed: {}", command_history.records.len());
println!(" Agent Learning: Active");
println!(" Context Enrichment: Enabled");
println!(" Performance Tracking: Real-time");
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🚀 Enhanced Atomic Server Configuration with Multi-Agent System");
println!("==============================================================\n");
// Run all demonstrations
demonstrate_config_evolution().await?;
demonstrate_intelligent_queries().await?;
demonstrate_context_integration().await?;
demonstrate_evolution_comparison().await?;
println!("\n🎉 All demonstrations completed successfully!");
println!("\n✅ Key Achievements:");
println!(" • Traditional Role configurations seamlessly evolve into intelligent agents");
println!(" • Atomic server data becomes accessible through AI-powered interfaces");
println!(" • Context enrichment provides comprehensive understanding");
println!(" • Multi-layered intelligence enhances every query");
println!(" • Performance tracking enables continuous optimization");
println!(
"\n🚀 The Multi-Agent System transforms static configurations into intelligent, adaptive agents!"
);
Ok(())
}