forest_of_agents/
forest_of_agents.rs

1//! # Forest of Agents Example
2//!
3//! This example demonstrates the Forest of Agents feature with STREAMING enabled by default.
4//! Watch as multiple agents collaborate in real-time, with their responses streaming
5//! token-by-token as they think and communicate.
6//!
7//! The Forest of Agents enables:
8//! - Inter-agent communication and messaging (with streaming responses)
9//! - Task delegation between agents
10//! - Shared context and memory
11//! - Collaborative task execution with real-time output
12//!
13//! Run this example with: `cargo run --example forest_of_agents`
14
15use helios_engine::{Agent, Config, ForestBuilder};
16use std::io::{self, Write};
17
18#[tokio::main]
19async fn main() -> helios_engine::Result<()> {
20    println!("🚀 Helios Engine - Forest of Agents Demo (with Real-Time Streaming)");
21    println!("====================================================================\n");
22    println!("💡 Note: All agent responses stream in real-time, token by token!\n");
23
24    // Load configuration
25    let config = Config::from_file("config.toml")?;
26
27    // Create a Forest of Agents with specialized agents
28    // You can add as many agents as you want!
29    let mut forest = ForestBuilder::new()
30        .config(config)
31        // Coordinator agent - manages the team and delegates tasks
32        .agent(
33            "coordinator".to_string(),
34            Agent::builder("coordinator")
35                .system_prompt(
36                    "You are a project coordinator responsible for breaking down complex tasks \
37                    and delegating them to specialized team members. You communicate with other \
38                    agents to ensure the project is completed successfully. Use the available \
39                    communication tools to delegate tasks, share information, and coordinate work."
40                )
41        )
42        // Research agent - gathers and analyzes information
43        .agent(
44            "researcher".to_string(),
45            Agent::builder("researcher")
46                .system_prompt(
47                    "You are a research specialist who excels at gathering information, \
48                    analyzing data, and providing insights. You work closely with the coordinator \
49                    and writer to ensure all work is based on accurate information. Use \
50                    communication tools to share your findings and request clarification when needed."
51                )
52        )
53        // Writer agent - creates content and documentation
54        .agent(
55            "writer".to_string(),
56            Agent::builder("writer")
57                .system_prompt(
58                    "You are a skilled writer who creates clear, well-structured content and \
59                    documentation. You work with the coordinator and researcher to produce \
60                    high-quality written materials. Use communication tools to request information \
61                    from the researcher and coordinate with the coordinator on project requirements."
62                )
63        )
64        // Editor agent - reviews and improves content
65        .agent(
66            "editor".to_string(),
67            Agent::builder("editor")
68                .system_prompt(
69                    "You are an editor who reviews content for quality, clarity, and consistency. \
70                    You provide feedback to the writer and ensure the final product meets high \
71                    standards. Use communication tools to request revisions and share feedback."
72                )
73        )
74        // Quality Assurance agent - validates the final output
75        .agent(
76            "qa".to_string(),
77            Agent::builder("qa")
78                .system_prompt(
79                    "You are a quality assurance specialist who validates that all requirements \
80                    are met and the output is accurate and complete. You work with all team members \
81                    to ensure the final deliverable is of the highest quality."
82                )
83        )
84        .max_iterations(5)
85        .build()
86        .await?;
87
88    println!("✅ Created Forest of Agents with 5 specialized agents:");
89    println!("  • 🎯 Coordinator: Manages projects and delegates tasks");
90    println!("  • 🔬 Researcher: Gathers and analyzes information");
91    println!("  • ✍️  Writer: Creates content and documentation");
92    println!("  • 📝 Editor: Reviews and improves content quality");
93    println!("  • ✅ QA: Validates requirements and final output");
94    println!();
95
96    // Demonstrate collaborative task execution with streaming
97    println!("🎯 TASK: Create a brief guide on sustainable gardening");
98    println!("{}", "=".repeat(70));
99    println!();
100
101    println!("🎬 Starting collaborative task execution...");
102    println!("   (Watch the responses stream in real-time!)\n");
103
104    // Simpler task for demonstration
105    let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
106                Include key benefits and one practical technique.";
107
108    println!("📋 Task Description:");
109    println!("   {}\n", task);
110
111    println!("{}", "─".repeat(70));
112    println!("🤖 COORDINATOR (streaming response):");
113    print!("   ");
114    io::stdout().flush()?;
115
116    let _result = forest
117        .execute_collaborative_task(
118            &"coordinator".to_string(),
119            task.to_string(),
120            vec!["researcher".to_string(), "writer".to_string()],
121        )
122        .await?;
123
124    println!();
125    println!("{}", "─".repeat(70));
126    println!();
127    println!("✨ Collaborative task completed!");
128    println!();
129
130    // Demonstrate direct agent communication with streaming
131    println!("💬 Testing direct agent-to-agent communication with streaming:");
132    println!("{}", "─".repeat(70));
133    println!();
134
135    let mut forest_clone = forest;
136
137    // Test a simple chat to show streaming
138    println!("📤 Sending task to Writer agent...");
139    println!("🤖 WRITER (streaming response):");
140    print!("   ");
141    io::stdout().flush()?;
142
143    if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
144        let _response = writer
145            .chat("Write one short paragraph about composting.")
146            .await?;
147        println!();
148    }
149
150    println!();
151    println!("{}", "─".repeat(70));
152    println!();
153
154    // Send a direct message between agents
155    println!("📤 Coordinator → Researcher: Direct message");
156    forest_clone
157        .send_message(
158            &"coordinator".to_string(),
159            Some(&"researcher".to_string()),
160            "Great job on the research! The information was very helpful.".to_string(),
161        )
162        .await?;
163
164    forest_clone.process_messages().await?;
165
166    if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
167        let messages = researcher.chat_session().messages.clone();
168        if let Some(last_msg) = messages.last() {
169            println!("📥 Researcher received: \"{}\"", last_msg.content);
170        }
171    }
172    println!();
173
174    // Demonstrate shared context
175    println!("🧠 Shared Context Demo:");
176    println!("{}", "─".repeat(70));
177    forest_clone
178        .set_shared_context(
179            "project_status".to_string(),
180            serde_json::json!({
181                "name": "Sustainable Gardening Guide",
182                "status": "completed",
183                "contributors": ["coordinator", "researcher", "writer"],
184                "completion_date": "2025-11-03"
185            }),
186        )
187        .await;
188
189    let context = forest_clone.get_shared_context().await;
190    if let Some(status) = context.get("project_status") {
191        println!("📊 Shared project status:");
192        println!("{}", serde_json::to_string_pretty(&status).unwrap());
193    }
194    println!();
195
196    println!("{}", "=".repeat(70));
197    println!("✅ Forest of Agents Demo Completed Successfully!");
198    println!("{}", "=".repeat(70));
199    println!();
200    println!("🎉 Key Features Demonstrated:");
201    println!("  ✓ Real-time streaming responses from all agents");
202    println!("  ✓ Multi-agent collaboration on tasks");
203    println!("  ✓ Inter-agent communication (direct messages)");
204    println!("  ✓ Task delegation and coordination");
205    println!("  ✓ Shared context and memory");
206    println!("  ✓ Specialized agent roles working together");
207    println!();
208    println!("💡 Notice how all responses streamed token-by-token in real-time!");
209    println!("   This provides immediate feedback and better user experience.");
210
211    Ok(())
212}