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. For simple tasks that you can handle yourself, \
37                    complete them directly and provide a complete response. For complex tasks that \
38                    require specialized expertise, you can delegate using the 'delegate_task' tool \
39                    to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
40                    When you delegate a task, WAIT for the response and then synthesize the results. \
41                    Always provide a final, complete answer to the user's request."
42                )
43                .max_iterations(10)
44        )
45        // Research agent - gathers and analyzes information
46        .agent(
47            "researcher".to_string(),
48            Agent::builder("researcher")
49                .system_prompt(
50                    "You are a research specialist who excels at gathering information, \
51                    analyzing data, and providing insights. You work closely with the coordinator \
52                    and writer to ensure all work is based on accurate information. Use \
53                    communication tools to share your findings and request clarification when needed."
54                )
55                .max_iterations(10)
56        )
57        // Writer agent - creates content and documentation
58        .agent(
59            "writer".to_string(),
60            Agent::builder("writer")
61                .system_prompt(
62                    "You are a skilled writer who creates clear, well-structured content and \
63                    documentation. When you receive a task, complete it fully and provide the \
64                    final written content. You can use communication tools to request information \
65                    from the researcher if needed."
66                )
67                .max_iterations(10)
68        )
69        // Editor agent - reviews and improves content
70        .agent(
71            "editor".to_string(),
72            Agent::builder("editor")
73                .system_prompt(
74                    "You are an editor who reviews content for quality, clarity, and consistency. \
75                    When you receive content to review, provide constructive feedback and an \
76                    improved version."
77                )
78                .max_iterations(10)
79        )
80        // Quality Assurance agent - validates the final output
81        .agent(
82            "qa".to_string(),
83            Agent::builder("qa")
84                .system_prompt(
85                    "You are a quality assurance specialist who validates that all requirements \
86                    are met and the output is accurate and complete. When you receive content to \
87                    review, verify it meets all requirements and provide your assessment."
88                )
89                .max_iterations(10)
90        )
91        .max_iterations(15)
92        .build()
93        .await?;
94
95    println!("✅ Created Forest of Agents with 5 specialized agents:");
96    println!("  • 🎯 Coordinator: Manages projects and delegates tasks");
97    println!("  • 🔬 Researcher: Gathers and analyzes information");
98    println!("  • ✍️  Writer: Creates content and documentation");
99    println!("  • 📝 Editor: Reviews and improves content quality");
100    println!("  • ✅ QA: Validates requirements and final output");
101    println!();
102
103    // Demonstrate collaborative task execution with streaming
104    println!("🎯 TASK: Create a brief guide on sustainable gardening");
105    println!("{}", "=".repeat(70));
106    println!();
107
108    println!("🎬 Starting collaborative task execution...");
109    println!("   (Watch the responses stream in real-time!)\n");
110
111    // Simpler task for demonstration
112    let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
113                Include key benefits and one practical technique.";
114
115    println!("📋 Task Description:");
116    println!("   {}\n", task);
117
118    println!("{}", "─".repeat(70));
119    println!("🤖 COORDINATOR (streaming response):");
120    print!("   ");
121    io::stdout().flush()?;
122
123    let _result = forest
124        .execute_collaborative_task(
125            &"coordinator".to_string(),
126            task.to_string(),
127            vec![
128                "researcher".to_string(),
129                "writer".to_string(),
130                "editor".to_string(),
131                "qa".to_string(),
132            ],
133        )
134        .await?;
135
136    println!();
137    println!("{}", "─".repeat(70));
138    println!();
139    println!("✨ Collaborative task completed!");
140    println!();
141
142    // Demonstrate direct agent communication with streaming
143    println!("💬 Testing direct agent-to-agent communication with streaming:");
144    println!("{}", "─".repeat(70));
145    println!();
146
147    let mut forest_clone = forest;
148
149    // Test a simple chat to show streaming
150    println!("📤 Sending task to Writer agent...");
151    println!("🤖 WRITER (streaming response):");
152    print!("   ");
153    io::stdout().flush()?;
154
155    if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
156        let _response = writer
157            .chat("Write one short paragraph about composting.")
158            .await?;
159        println!();
160    }
161
162    println!();
163    println!("{}", "─".repeat(70));
164    println!();
165
166    // Send a direct message between agents
167    println!("📤 Coordinator → Researcher: Direct message");
168    forest_clone
169        .send_message(
170            &"coordinator".to_string(),
171            Some(&"researcher".to_string()),
172            "Great job on the research! The information was very helpful.".to_string(),
173        )
174        .await?;
175
176    forest_clone.process_messages().await?;
177
178    if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
179        let messages = researcher.chat_session().messages.clone();
180        if let Some(last_msg) = messages.last() {
181            println!("📥 Researcher received: \"{}\"", last_msg.content);
182        }
183    }
184    println!();
185
186    // Demonstrate shared context
187    println!("🧠 Shared Context Demo:");
188    println!("{}", "─".repeat(70));
189    forest_clone
190        .set_shared_context(
191            "project_status".to_string(),
192            serde_json::json!({
193                "name": "Sustainable Gardening Guide",
194                "status": "completed",
195                "contributors": ["coordinator", "researcher", "writer"],
196                "completion_date": "2025-11-03"
197            }),
198        )
199        .await;
200
201    let context = forest_clone.get_shared_context().await;
202    if let Some(status) = context.get("project_status") {
203        println!("📊 Shared project status:");
204        println!("{}", serde_json::to_string_pretty(&status).unwrap());
205    }
206    println!();
207
208    println!("{}", "=".repeat(70));
209    println!("✅ Forest of Agents Demo Completed Successfully!");
210    println!("{}", "=".repeat(70));
211    println!();
212    println!("🎉 Key Features Demonstrated:");
213    println!("  ✓ Real-time streaming responses from all agents");
214    println!("  ✓ Multi-agent collaboration on tasks");
215    println!("  ✓ Inter-agent communication (direct messages)");
216    println!("  ✓ Task delegation and coordination");
217    println!("  ✓ Shared context and memory");
218    println!("  ✓ Specialized agent roles working together");
219    println!();
220    println!("💡 Notice how all responses streamed token-by-token in real-time!");
221    println!("   This provides immediate feedback and better user experience.");
222
223    Ok(())
224}