forest_of_agents/
forest_of_agents.rs

1//! # Forest of Agents Example
2//!
3//! This example demonstrates the Forest of Agents feature, which allows multiple agents
4//! to collaborate, communicate, and share context to accomplish complex tasks together.
5//!
6//! The Forest of Agents enables:
7//! - Inter-agent communication and messaging
8//! - Task delegation between agents
9//! - Shared context and memory
10//! - Collaborative task execution
11//!
12//! Run this example with: `cargo run --example forest_of_agents`
13
14use helios_engine::{Agent, Config, ForestBuilder};
15
16#[tokio::main]
17async fn main() -> helios_engine::Result<()> {
18    println!("šŸš€ Helios Engine - Forest of Agents Demo");
19    println!("=========================================\n");
20
21    // Load configuration
22    let config = Config::from_file("config.toml")?;
23
24    // Create a Forest of Agents with specialized agents
25    let mut forest = ForestBuilder::new()
26        .config(config)
27        // Coordinator agent - manages the team and delegates tasks
28        .agent(
29            "coordinator".to_string(),
30            Agent::builder("coordinator")
31                .system_prompt(
32                    "You are a project coordinator responsible for breaking down complex tasks \
33                    and delegating them to specialized team members. You communicate with other \
34                    agents to ensure the project is completed successfully. Use the available \
35                    communication tools to delegate tasks, share information, and coordinate work."
36                )
37        )
38        // Research agent - gathers and analyzes information
39        .agent(
40            "researcher".to_string(),
41            Agent::builder("researcher")
42                .system_prompt(
43                    "You are a research specialist who excels at gathering information, \
44                    analyzing data, and providing insights. You work closely with the coordinator \
45                    and writer to ensure all work is based on accurate information. Use \
46                    communication tools to share your findings and request clarification when needed."
47                )
48        )
49        // Writer agent - creates content and documentation
50        .agent(
51            "writer".to_string(),
52            Agent::builder("writer")
53                .system_prompt(
54                    "You are a skilled writer who creates clear, well-structured content and \
55                    documentation. You work with the coordinator and researcher to produce \
56                    high-quality written materials. Use communication tools to request information \
57                    from the researcher and coordinate with the coordinator on project requirements."
58                )
59        )
60        .max_iterations(5)
61        .build()
62        .await?;
63
64    println!("āœ“ Created Forest of Agents with 3 specialized agents:");
65    println!("  • Coordinator: Manages projects and delegates tasks");
66    println!("  • Researcher: Gathers and analyzes information");
67    println!("  • Writer: Creates content and documentation");
68    println!();
69
70    // Demonstrate collaborative task execution
71    println!("šŸŽÆ Executing collaborative task:");
72    println!("\"Create a comprehensive guide on sustainable gardening practices\"");
73    println!();
74
75    let result = forest
76        .execute_collaborative_task(
77            &"coordinator".to_string(),
78            "Create a comprehensive guide on sustainable gardening practices. This should include \
79            environmental benefits, practical techniques, common challenges, and tips for beginners. \
80            Make it informative yet accessible to people new to sustainable gardening.".to_string(),
81            vec![
82                "researcher".to_string(),
83                "writer".to_string(),
84            ],
85        )
86        .await?;
87
88    println!("šŸ“„ Final Result:");
89    println!("{}", "=".repeat(60));
90    println!("{}", result);
91    println!("{}", "=".repeat(60));
92    println!();
93
94    // Demonstrate direct agent communication
95    println!("šŸ’¬ Demonstrating inter-agent communication:");
96    println!();
97
98    let mut forest_clone = forest; // Clone for mutable operations
99
100    // Send a direct message
101    println!("šŸ“¤ Coordinator sends a message to Researcher...");
102    forest_clone
103        .send_message(
104            &"coordinator".to_string(),
105            Some(&"researcher".to_string()),
106            "Please research the latest sustainable gardening techniques for urban environments."
107                .to_string(),
108        )
109        .await?;
110
111    // Process messages
112    forest_clone.process_messages().await?;
113
114    // Check what the researcher received
115    if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
116        let messages = researcher.chat_session().messages.clone();
117        if let Some(last_msg) = messages.last() {
118            println!("šŸ“„ Researcher received: {}", last_msg.content);
119        }
120    }
121
122    // Send a broadcast message
123    println!("\nšŸ“¢ Coordinator broadcasts an update...");
124    forest_clone
125        .send_message(
126            &"coordinator".to_string(),
127            None, // None = broadcast
128            "Team update: We've successfully completed the sustainable gardening guide. Great collaboration everyone!".to_string(),
129        )
130        .await?;
131
132    forest_clone.process_messages().await?;
133
134    // Check what agents received
135    for agent_id in ["coordinator", "researcher", "writer"] {
136        if let Some(agent) = forest_clone.get_agent(&agent_id.to_string()) {
137            let messages = agent.chat_session().messages.clone();
138            if let Some(last_msg) = messages.last() {
139                if last_msg.content.contains("broadcast") {
140                    println!("šŸ“„ {} received broadcast: {}", agent_id, last_msg.content);
141                }
142            }
143        }
144    }
145
146    // Demonstrate shared context
147    println!("\n🧠 Demonstrating shared context:");
148    forest_clone
149        .set_shared_context(
150            "project_status".to_string(),
151            serde_json::json!({
152                "name": "Sustainable Gardening Guide",
153                "status": "completed",
154                "contributors": ["coordinator", "researcher", "writer"],
155                "completion_date": "2025-11-02"
156            }),
157        )
158        .await;
159
160    let context = forest_clone.get_shared_context().await;
161    if let Some(status) = context.get("project_status") {
162        println!("šŸ“Š Shared project status: {}", status);
163    }
164
165    println!("\nāœ… Forest of Agents demo completed successfully!");
166    println!("\nKey features demonstrated:");
167    println!("  • Multi-agent collaboration on complex tasks");
168    println!("  • Inter-agent communication (direct and broadcast)");
169    println!("  • Task delegation and coordination");
170    println!("  • Shared context and memory");
171    println!("  • Specialized agent roles working together");
172
173    Ok(())
174}