pub struct ForestOfAgents { /* private fields */ }Expand description
The main Forest of Agents structure that manages multiple agents.
Implementations§
Source§impl ForestOfAgents
impl ForestOfAgents
Sourcepub fn with_max_iterations(max_iterations: usize) -> Self
pub fn with_max_iterations(max_iterations: usize) -> Self
Creates a new Forest of Agents with the specified max iterations.
Sourcepub fn remove_agent(&mut self, id: &AgentId) -> Option<Agent>
pub fn remove_agent(&mut self, id: &AgentId) -> Option<Agent>
Sourcepub fn get_agent(&self, id: &AgentId) -> Option<&Agent>
pub fn get_agent(&self, id: &AgentId) -> Option<&Agent>
Gets a reference to an agent by ID.
Examples found in repository?
examples/send_message_tool_demo.rs (line 144)
19async fn main() -> helios_engine::Result<()> {
20 println!("📨 Helios Engine - SendMessageTool Demo");
21 println!("=======================================\n");
22
23 // Load configuration
24 let config = Config::from_file("config.toml")?;
25 println!("✓ Loaded configuration from config.toml");
26
27 // Create a simple forest with two agents
28 let mut forest = ForestBuilder::new()
29 .config(config)
30 .agent(
31 "alice".to_string(),
32 Agent::builder("alice")
33 .system_prompt("You are Alice, a helpful communication assistant."),
34 )
35 .agent(
36 "bob".to_string(),
37 Agent::builder("bob")
38 .system_prompt("You are Bob, a friendly colleague who responds to messages."),
39 )
40 .max_iterations(3)
41 .build()
42 .await?;
43
44 println!("✓ Created Forest with 2 agents: Alice and Bob");
45 println!();
46
47 // Demonstrate SendMessageTool direct messaging
48 println!("📤 Testing SendMessageTool - Direct Message:");
49 println!("---------------------------------------------");
50
51 // Create the tool for Alice
52 let message_queue = Arc::new(RwLock::new(Vec::new()));
53 let shared_context = Arc::new(RwLock::new(helios_engine::SharedContext::new()));
54
55 let send_tool = SendMessageTool::new(
56 "alice".to_string(),
57 Arc::clone(&message_queue),
58 Arc::clone(&shared_context),
59 );
60
61 // Test 1: Send a direct message from Alice to Bob
62 println!("1. Alice sends a direct message to Bob...");
63
64 let direct_message_args = serde_json::json!({
65 "to": "bob",
66 "message": "Hi Bob! How are you doing today?"
67 });
68
69 let result = send_tool.execute(direct_message_args).await?;
70 println!(" Tool result: {}", result.output);
71 println!(" Success: {}", result.success);
72
73 // Check the message queue
74 {
75 let queue = message_queue.read().await;
76 println!(" Messages in queue: {}", queue.len());
77 if let Some(msg) = queue.first() {
78 println!(" Message details:");
79 println!(" From: {}", msg.from);
80 println!(" To: {:?}", msg.to);
81 println!(" Content: {}", msg.content);
82 }
83 }
84
85 // Check shared context
86 {
87 let context = shared_context.read().await;
88 let messages = context.get_recent_messages(10);
89 println!(" Messages in shared context: {}", messages.len());
90 }
91
92 println!();
93
94 // Test 2: Send a broadcast message
95 println!("2. Alice broadcasts a message to everyone...");
96
97 let broadcast_message_args = serde_json::json!({
98 "message": "Hello everyone! This is a broadcast message from Alice."
99 });
100
101 let result2 = send_tool.execute(broadcast_message_args).await?;
102 println!(" Tool result: {}", result2.output);
103 println!(" Success: {}", result2.success);
104
105 // Check the message queue after broadcast
106 {
107 let queue = message_queue.read().await;
108 println!(" Messages in queue: {}", queue.len());
109 if let Some(msg) = queue.last() {
110 println!(" Latest message details:");
111 println!(" From: {}", msg.from);
112 println!(" To: {:?}", msg.to);
113 println!(" Content: {}", msg.content);
114 }
115 }
116
117 println!();
118
119 // Demonstrate integration with Forest messaging system
120 println!("🌲 Testing Forest Integration:");
121 println!("------------------------------");
122
123 // Clear our test queues and use the forest's messaging system
124 {
125 let mut queue = message_queue.write().await;
126 queue.clear();
127 }
128
129 println!("3. Using Forest's messaging system...");
130
131 // Send message through the forest
132 forest
133 .send_message(
134 &"alice".to_string(),
135 Some(&"bob".to_string()),
136 "Hello Bob via Forest messaging!".to_string(),
137 )
138 .await?;
139
140 // Process messages
141 forest.process_messages().await?;
142
143 // Check if Bob received the message
144 if let Some(bob) = forest.get_agent(&"bob".to_string()) {
145 let messages = bob.chat_session().messages.clone();
146 println!(" Bob's message count: {}", messages.len());
147 if let Some(last_msg) = messages.last() {
148 println!(" Bob received: {}", last_msg.content);
149 }
150 }
151
152 println!();
153
154 // Test broadcast through forest
155 println!("4. Forest broadcast message...");
156
157 forest
158 .send_message(
159 &"alice".to_string(),
160 None, // Broadcast
161 "Forest broadcast: Meeting at 3 PM!".to_string(),
162 )
163 .await?;
164
165 forest.process_messages().await?;
166
167 // Check all agents received the broadcast
168 for agent_id in ["alice", "bob"] {
169 if let Some(agent) = forest.get_agent(&agent_id.to_string()) {
170 let messages = agent.chat_session().messages.clone();
171 if let Some(last_msg) = messages.last() {
172 if last_msg.content.contains("broadcast") || last_msg.content.contains("Meeting") {
173 println!(" {} received broadcast: {}", agent_id, last_msg.content);
174 }
175 }
176 }
177 }
178
179 println!();
180 println!("✅ SendMessageTool demo completed successfully!");
181 println!();
182 println!("Key features tested:");
183 println!(" • Direct messaging between agents");
184 println!(" • Broadcast messaging to all agents");
185 println!(" • Message queue management");
186 println!(" • Shared context integration");
187 println!(" • Forest messaging system integration");
188
189 Ok(())
190}More examples
examples/forest_of_agents.rs (line 180)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}Sourcepub fn get_agent_mut(&mut self, id: &AgentId) -> Option<&mut Agent>
pub fn get_agent_mut(&mut self, id: &AgentId) -> Option<&mut Agent>
Gets a mutable reference to an agent by ID.
Examples found in repository?
examples/forest_of_agents.rs (line 157)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}Sourcepub fn list_agents(&self) -> Vec<AgentId> ⓘ
pub fn list_agents(&self) -> Vec<AgentId> ⓘ
Lists all agent IDs in the forest.
Sourcepub async fn send_message(
&self,
from: &AgentId,
to: Option<&AgentId>,
content: String,
) -> Result<()>
pub async fn send_message( &self, from: &AgentId, to: Option<&AgentId>, content: String, ) -> Result<()>
Sends a message from one agent to another.
§Arguments
from- ID of the sending agentto- ID of the receiving agent (None for broadcast)content- Message content
§Returns
Returns an error if the sender doesn’t exist.
Examples found in repository?
examples/send_message_tool_demo.rs (lines 133-137)
19async fn main() -> helios_engine::Result<()> {
20 println!("📨 Helios Engine - SendMessageTool Demo");
21 println!("=======================================\n");
22
23 // Load configuration
24 let config = Config::from_file("config.toml")?;
25 println!("✓ Loaded configuration from config.toml");
26
27 // Create a simple forest with two agents
28 let mut forest = ForestBuilder::new()
29 .config(config)
30 .agent(
31 "alice".to_string(),
32 Agent::builder("alice")
33 .system_prompt("You are Alice, a helpful communication assistant."),
34 )
35 .agent(
36 "bob".to_string(),
37 Agent::builder("bob")
38 .system_prompt("You are Bob, a friendly colleague who responds to messages."),
39 )
40 .max_iterations(3)
41 .build()
42 .await?;
43
44 println!("✓ Created Forest with 2 agents: Alice and Bob");
45 println!();
46
47 // Demonstrate SendMessageTool direct messaging
48 println!("📤 Testing SendMessageTool - Direct Message:");
49 println!("---------------------------------------------");
50
51 // Create the tool for Alice
52 let message_queue = Arc::new(RwLock::new(Vec::new()));
53 let shared_context = Arc::new(RwLock::new(helios_engine::SharedContext::new()));
54
55 let send_tool = SendMessageTool::new(
56 "alice".to_string(),
57 Arc::clone(&message_queue),
58 Arc::clone(&shared_context),
59 );
60
61 // Test 1: Send a direct message from Alice to Bob
62 println!("1. Alice sends a direct message to Bob...");
63
64 let direct_message_args = serde_json::json!({
65 "to": "bob",
66 "message": "Hi Bob! How are you doing today?"
67 });
68
69 let result = send_tool.execute(direct_message_args).await?;
70 println!(" Tool result: {}", result.output);
71 println!(" Success: {}", result.success);
72
73 // Check the message queue
74 {
75 let queue = message_queue.read().await;
76 println!(" Messages in queue: {}", queue.len());
77 if let Some(msg) = queue.first() {
78 println!(" Message details:");
79 println!(" From: {}", msg.from);
80 println!(" To: {:?}", msg.to);
81 println!(" Content: {}", msg.content);
82 }
83 }
84
85 // Check shared context
86 {
87 let context = shared_context.read().await;
88 let messages = context.get_recent_messages(10);
89 println!(" Messages in shared context: {}", messages.len());
90 }
91
92 println!();
93
94 // Test 2: Send a broadcast message
95 println!("2. Alice broadcasts a message to everyone...");
96
97 let broadcast_message_args = serde_json::json!({
98 "message": "Hello everyone! This is a broadcast message from Alice."
99 });
100
101 let result2 = send_tool.execute(broadcast_message_args).await?;
102 println!(" Tool result: {}", result2.output);
103 println!(" Success: {}", result2.success);
104
105 // Check the message queue after broadcast
106 {
107 let queue = message_queue.read().await;
108 println!(" Messages in queue: {}", queue.len());
109 if let Some(msg) = queue.last() {
110 println!(" Latest message details:");
111 println!(" From: {}", msg.from);
112 println!(" To: {:?}", msg.to);
113 println!(" Content: {}", msg.content);
114 }
115 }
116
117 println!();
118
119 // Demonstrate integration with Forest messaging system
120 println!("🌲 Testing Forest Integration:");
121 println!("------------------------------");
122
123 // Clear our test queues and use the forest's messaging system
124 {
125 let mut queue = message_queue.write().await;
126 queue.clear();
127 }
128
129 println!("3. Using Forest's messaging system...");
130
131 // Send message through the forest
132 forest
133 .send_message(
134 &"alice".to_string(),
135 Some(&"bob".to_string()),
136 "Hello Bob via Forest messaging!".to_string(),
137 )
138 .await?;
139
140 // Process messages
141 forest.process_messages().await?;
142
143 // Check if Bob received the message
144 if let Some(bob) = forest.get_agent(&"bob".to_string()) {
145 let messages = bob.chat_session().messages.clone();
146 println!(" Bob's message count: {}", messages.len());
147 if let Some(last_msg) = messages.last() {
148 println!(" Bob received: {}", last_msg.content);
149 }
150 }
151
152 println!();
153
154 // Test broadcast through forest
155 println!("4. Forest broadcast message...");
156
157 forest
158 .send_message(
159 &"alice".to_string(),
160 None, // Broadcast
161 "Forest broadcast: Meeting at 3 PM!".to_string(),
162 )
163 .await?;
164
165 forest.process_messages().await?;
166
167 // Check all agents received the broadcast
168 for agent_id in ["alice", "bob"] {
169 if let Some(agent) = forest.get_agent(&agent_id.to_string()) {
170 let messages = agent.chat_session().messages.clone();
171 if let Some(last_msg) = messages.last() {
172 if last_msg.content.contains("broadcast") || last_msg.content.contains("Meeting") {
173 println!(" {} received broadcast: {}", agent_id, last_msg.content);
174 }
175 }
176 }
177 }
178
179 println!();
180 println!("✅ SendMessageTool demo completed successfully!");
181 println!();
182 println!("Key features tested:");
183 println!(" • Direct messaging between agents");
184 println!(" • Broadcast messaging to all agents");
185 println!(" • Message queue management");
186 println!(" • Shared context integration");
187 println!(" • Forest messaging system integration");
188
189 Ok(())
190}More examples
examples/forest_of_agents.rs (lines 171-175)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}Sourcepub async fn process_messages(&mut self) -> Result<()>
pub async fn process_messages(&mut self) -> Result<()>
Processes pending messages in the queue.
Examples found in repository?
examples/send_message_tool_demo.rs (line 141)
19async fn main() -> helios_engine::Result<()> {
20 println!("📨 Helios Engine - SendMessageTool Demo");
21 println!("=======================================\n");
22
23 // Load configuration
24 let config = Config::from_file("config.toml")?;
25 println!("✓ Loaded configuration from config.toml");
26
27 // Create a simple forest with two agents
28 let mut forest = ForestBuilder::new()
29 .config(config)
30 .agent(
31 "alice".to_string(),
32 Agent::builder("alice")
33 .system_prompt("You are Alice, a helpful communication assistant."),
34 )
35 .agent(
36 "bob".to_string(),
37 Agent::builder("bob")
38 .system_prompt("You are Bob, a friendly colleague who responds to messages."),
39 )
40 .max_iterations(3)
41 .build()
42 .await?;
43
44 println!("✓ Created Forest with 2 agents: Alice and Bob");
45 println!();
46
47 // Demonstrate SendMessageTool direct messaging
48 println!("📤 Testing SendMessageTool - Direct Message:");
49 println!("---------------------------------------------");
50
51 // Create the tool for Alice
52 let message_queue = Arc::new(RwLock::new(Vec::new()));
53 let shared_context = Arc::new(RwLock::new(helios_engine::SharedContext::new()));
54
55 let send_tool = SendMessageTool::new(
56 "alice".to_string(),
57 Arc::clone(&message_queue),
58 Arc::clone(&shared_context),
59 );
60
61 // Test 1: Send a direct message from Alice to Bob
62 println!("1. Alice sends a direct message to Bob...");
63
64 let direct_message_args = serde_json::json!({
65 "to": "bob",
66 "message": "Hi Bob! How are you doing today?"
67 });
68
69 let result = send_tool.execute(direct_message_args).await?;
70 println!(" Tool result: {}", result.output);
71 println!(" Success: {}", result.success);
72
73 // Check the message queue
74 {
75 let queue = message_queue.read().await;
76 println!(" Messages in queue: {}", queue.len());
77 if let Some(msg) = queue.first() {
78 println!(" Message details:");
79 println!(" From: {}", msg.from);
80 println!(" To: {:?}", msg.to);
81 println!(" Content: {}", msg.content);
82 }
83 }
84
85 // Check shared context
86 {
87 let context = shared_context.read().await;
88 let messages = context.get_recent_messages(10);
89 println!(" Messages in shared context: {}", messages.len());
90 }
91
92 println!();
93
94 // Test 2: Send a broadcast message
95 println!("2. Alice broadcasts a message to everyone...");
96
97 let broadcast_message_args = serde_json::json!({
98 "message": "Hello everyone! This is a broadcast message from Alice."
99 });
100
101 let result2 = send_tool.execute(broadcast_message_args).await?;
102 println!(" Tool result: {}", result2.output);
103 println!(" Success: {}", result2.success);
104
105 // Check the message queue after broadcast
106 {
107 let queue = message_queue.read().await;
108 println!(" Messages in queue: {}", queue.len());
109 if let Some(msg) = queue.last() {
110 println!(" Latest message details:");
111 println!(" From: {}", msg.from);
112 println!(" To: {:?}", msg.to);
113 println!(" Content: {}", msg.content);
114 }
115 }
116
117 println!();
118
119 // Demonstrate integration with Forest messaging system
120 println!("🌲 Testing Forest Integration:");
121 println!("------------------------------");
122
123 // Clear our test queues and use the forest's messaging system
124 {
125 let mut queue = message_queue.write().await;
126 queue.clear();
127 }
128
129 println!("3. Using Forest's messaging system...");
130
131 // Send message through the forest
132 forest
133 .send_message(
134 &"alice".to_string(),
135 Some(&"bob".to_string()),
136 "Hello Bob via Forest messaging!".to_string(),
137 )
138 .await?;
139
140 // Process messages
141 forest.process_messages().await?;
142
143 // Check if Bob received the message
144 if let Some(bob) = forest.get_agent(&"bob".to_string()) {
145 let messages = bob.chat_session().messages.clone();
146 println!(" Bob's message count: {}", messages.len());
147 if let Some(last_msg) = messages.last() {
148 println!(" Bob received: {}", last_msg.content);
149 }
150 }
151
152 println!();
153
154 // Test broadcast through forest
155 println!("4. Forest broadcast message...");
156
157 forest
158 .send_message(
159 &"alice".to_string(),
160 None, // Broadcast
161 "Forest broadcast: Meeting at 3 PM!".to_string(),
162 )
163 .await?;
164
165 forest.process_messages().await?;
166
167 // Check all agents received the broadcast
168 for agent_id in ["alice", "bob"] {
169 if let Some(agent) = forest.get_agent(&agent_id.to_string()) {
170 let messages = agent.chat_session().messages.clone();
171 if let Some(last_msg) = messages.last() {
172 if last_msg.content.contains("broadcast") || last_msg.content.contains("Meeting") {
173 println!(" {} received broadcast: {}", agent_id, last_msg.content);
174 }
175 }
176 }
177 }
178
179 println!();
180 println!("✅ SendMessageTool demo completed successfully!");
181 println!();
182 println!("Key features tested:");
183 println!(" • Direct messaging between agents");
184 println!(" • Broadcast messaging to all agents");
185 println!(" • Message queue management");
186 println!(" • Shared context integration");
187 println!(" • Forest messaging system integration");
188
189 Ok(())
190}More examples
examples/forest_of_agents.rs (line 178)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}Sourcepub async fn execute_collaborative_task(
&mut self,
initiator: &AgentId,
task_description: String,
involved_agents: Vec<AgentId>,
) -> Result<String>
pub async fn execute_collaborative_task( &mut self, initiator: &AgentId, task_description: String, involved_agents: Vec<AgentId>, ) -> Result<String>
Executes a collaborative task across multiple agents with planning.
§Arguments
initiator- ID of the coordinator agent (must create the plan)task_description- Description of the overall taskinvolved_agents- IDs of agents available for task execution
§Returns
Returns the final result from the collaborative process.
Examples found in repository?
examples/forest_simple_demo.rs (lines 58-62)
9async fn main() -> helios_engine::Result<()> {
10 println!("🚀 Forest of Agents - Simple Demo\n");
11
12 let config = Config::from_file("config.toml")?;
13
14 // Create a simpler forest with just 3 agents
15 let mut forest = ForestBuilder::new()
16 .config(config)
17 .agent(
18 "coordinator".to_string(),
19 Agent::builder("coordinator")
20 .system_prompt(
21 "You are a project coordinator. Your ONLY job is to create plans, not execute tasks.\n\
22 When given a task, IMMEDIATELY use the create_plan tool with this format:\n\
23 - objective: the overall goal\n\
24 - tasks: JSON array with structure [{\"id\":\"task_1\",\"description\":\"...\",\"assigned_to\":\"worker1\",\"dependencies\":[]}]\n\n\
25 Keep plans simple with 2-3 tasks max. Do NOT try to complete the task yourself."
26 )
27 .max_iterations(15)
28 )
29 .agent(
30 "worker1".to_string(),
31 Agent::builder("worker1")
32 .system_prompt(
33 "You are a helpful worker. Complete the task assigned to you and use the \
34 update_task_memory tool to save your results. Be brief and direct."
35 )
36 .max_iterations(8)
37 )
38 .agent(
39 "worker2".to_string(),
40 Agent::builder("worker2")
41 .system_prompt(
42 "You are a helpful worker. Complete the task assigned to you and use the \
43 update_task_memory tool to save your results. Be brief and direct."
44 )
45 .max_iterations(8)
46 )
47 .max_iterations(20)
48 .build()
49 .await?;
50
51 println!("✅ Forest created with 3 agents\n");
52
53 // Simple task
54 let task = "List 3 benefits of exercise. Keep it brief.";
55 println!("📋 Task: {}\n", task);
56
57 let result = forest
58 .execute_collaborative_task(
59 &"coordinator".to_string(),
60 task.to_string(),
61 vec!["worker1".to_string(), "worker2".to_string()],
62 )
63 .await?;
64
65 println!("\n{}\n", "=".repeat(60));
66 println!("✨ RESULT:\n{}\n", result);
67 println!("{}\n", "=".repeat(60));
68
69 // Show task breakdown
70 let context = forest.get_shared_context().await;
71 if let Some(plan) = context.get_plan() {
72 println!("📊 Plan Summary:");
73 let (completed, total) = plan.get_progress();
74 println!(" Completed: {}/{} tasks\n", completed, total);
75
76 for task in plan.tasks_in_order() {
77 let status = match task.status {
78 helios_engine::forest::TaskStatus::Completed => "✅",
79 helios_engine::forest::TaskStatus::InProgress => "🔄",
80 helios_engine::forest::TaskStatus::Pending => "⏳",
81 helios_engine::forest::TaskStatus::Failed => "❌",
82 };
83 println!(" {} [{}] {}", status, task.assigned_to, task.description);
84 }
85 } else {
86 println!("📊 No plan was created (coordinator handled directly)");
87 }
88
89 println!("\n✅ Demo completed!");
90
91 Ok(())
92}More examples
examples/forest_of_agents.rs (lines 126-135)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}examples/forest_with_coordinator.rs (lines 142-151)
19async fn main() -> helios_engine::Result<()> {
20 println!("🚀 Forest of Agents with Coordinator-Based Planning\n");
21
22 // Load configuration
23 let config = Config::from_file("config.toml")?;
24
25 // Create a Forest of Agents with specialized roles
26 let mut forest = ForestBuilder::new()
27 .config(config)
28 // Coordinator agent - creates plans and manages the team
29 .agent(
30 "coordinator".to_string(),
31 Agent::builder("coordinator")
32 .system_prompt(
33 "You are an expert project coordinator and task planner. Your role is to:\n\
34 1. Analyze complex tasks and break them into manageable subtasks\n\
35 2. Create detailed plans using the 'create_plan' tool\n\
36 3. Assign tasks to the most appropriate team members based on their expertise\n\
37 4. Define task dependencies to ensure proper execution order\n\
38 5. Synthesize final results from all team members\n\n\
39 Available team members:\n\
40 - researcher: Gathers information, conducts analysis, finds data\n\
41 - writer: Creates content, documentation, and written materials\n\
42 - analyst: Analyzes data, identifies patterns, provides insights\n\
43 - reviewer: Reviews work quality, provides feedback, ensures standards\n\n\
44 When creating a plan, think carefully about:\n\
45 - What information is needed first (research/data gathering)\n\
46 - What depends on what (task dependencies)\n\
47 - Who is best suited for each task\n\
48 - How to ensure quality (review steps)\n\n\
49 Always use the create_plan tool to structure the work.",
50 )
51 .max_iterations(20),
52 )
53 // Research agent - gathers information and data
54 .agent(
55 "researcher".to_string(),
56 Agent::builder("researcher")
57 .system_prompt(
58 "You are a research specialist who excels at:\n\
59 - Gathering comprehensive information on topics\n\
60 - Identifying key facts, statistics, and sources\n\
61 - Analyzing information for relevance and accuracy\n\
62 - Providing well-organized research findings\n\n\
63 When completing a task:\n\
64 1. Review the shared memory to see what other agents have done\n\
65 2. Conduct thorough research on your assigned topic\n\
66 3. Use 'update_task_memory' tool to save your findings\n\
67 4. Include key data points that other agents might need\n\n\
68 Be thorough but concise in your responses.",
69 )
70 .max_iterations(10),
71 )
72 // Writer agent - creates content
73 .agent(
74 "writer".to_string(),
75 Agent::builder("writer")
76 .system_prompt(
77 "You are a skilled content writer who excels at:\n\
78 - Creating clear, engaging, and well-structured content\n\
79 - Adapting tone and style to the audience\n\
80 - Incorporating research and data into narratives\n\
81 - Writing comprehensive yet accessible material\n\n\
82 When completing a task:\n\
83 1. Review the shared memory for research and data from other agents\n\
84 2. Create well-structured content based on the requirements\n\
85 3. Use 'update_task_memory' tool to save your written content\n\
86 4. Ensure your content is complete and ready for review\n\n\
87 Write clearly and professionally.",
88 )
89 .max_iterations(10),
90 )
91 // Analyst agent - analyzes data and provides insights
92 .agent(
93 "analyst".to_string(),
94 Agent::builder("analyst")
95 .system_prompt(
96 "You are a data analyst who excels at:\n\
97 - Analyzing information and identifying patterns\n\
98 - Drawing insights from data and research\n\
99 - Providing actionable recommendations\n\
100 - Summarizing complex information clearly\n\n\
101 When completing a task:\n\
102 1. Review the shared memory for available data and research\n\
103 2. Analyze the information thoroughly\n\
104 3. Use 'update_task_memory' tool to save your analysis and insights\n\
105 4. Provide clear, actionable conclusions\n\n\
106 Be analytical and data-driven in your responses.",
107 )
108 .max_iterations(10),
109 )
110 // Reviewer agent - ensures quality
111 .agent(
112 "reviewer".to_string(),
113 Agent::builder("reviewer")
114 .system_prompt(
115 "You are a quality reviewer who excels at:\n\
116 - Reviewing content for accuracy and completeness\n\
117 - Identifying areas for improvement\n\
118 - Ensuring consistency and quality standards\n\
119 - Providing constructive feedback\n\n\
120 When completing a task:\n\
121 1. Review the shared memory to see all completed work\n\
122 2. Evaluate the quality, accuracy, and completeness\n\
123 3. Use 'update_task_memory' tool to save your review and any improvements\n\
124 4. Provide clear assessment and final approval\n\n\
125 Be thorough and constructive in your reviews.",
126 )
127 .max_iterations(15),
128 )
129 .max_iterations(30)
130 .build()
131 .await?;
132
133 println!("✅ Forest created with 5 specialized agents\n");
134
135 let task1 = "Create a comprehensive guide about the benefits of renewable energy. \
136 Include research-backed information, clear explanations, data analysis, \
137 and ensure it's well-reviewed for quality.";
138
139 println!("📋 Task: {}\n", task1);
140
141 let result1 = forest
142 .execute_collaborative_task(
143 &"coordinator".to_string(),
144 task1.to_string(),
145 vec![
146 "researcher".to_string(),
147 "writer".to_string(),
148 "analyst".to_string(),
149 "reviewer".to_string(),
150 ],
151 )
152 .await?;
153
154 println!("\n{}\n", "=".repeat(70));
155 println!("✨ FINAL RESULT:\n{}\n", result1);
156 println!("{}\n", "=".repeat(70));
157
158 // Show the shared memory state
159 println!("📊 SHARED MEMORY STATE:");
160 let context = forest.get_shared_context().await;
161
162 if let Some(plan) = context.get_plan() {
163 println!("\n📋 Task Plan Summary:");
164 println!(" Objective: {}", plan.objective);
165 println!(" Total Tasks: {}", plan.tasks.len());
166 println!(
167 " Completed: {}/{}",
168 plan.get_progress().0,
169 plan.get_progress().1
170 );
171 println!("\n Task Breakdown:");
172 for task in plan.tasks_in_order() {
173 let status_icon = match task.status {
174 helios_engine::forest::TaskStatus::Completed => "✅",
175 helios_engine::forest::TaskStatus::InProgress => "🔄",
176 helios_engine::forest::TaskStatus::Pending => "⏳",
177 helios_engine::forest::TaskStatus::Failed => "❌",
178 };
179 println!(
180 " {} [{}] {} - {}",
181 status_icon, task.assigned_to, task.id, task.description
182 );
183 if let Some(result) = &task.result {
184 let preview = if result.len() > 100 {
185 format!("{}...", &result[..100])
186 } else {
187 result.clone()
188 };
189 println!(" Result: {}", preview);
190 }
191 }
192 }
193
194 println!("\n Shared Data Keys:");
195 for key in context.data.keys() {
196 if !key.starts_with("current_")
197 && !key.starts_with("involved_")
198 && !key.starts_with("task_status")
199 {
200 println!(" • {}", key);
201 }
202 }
203
204 println!("\n✅ Demo completed successfully!");
205
206 Ok(())
207}Gets the shared context.
Examples found in repository?
examples/forest_simple_demo.rs (line 70)
9async fn main() -> helios_engine::Result<()> {
10 println!("🚀 Forest of Agents - Simple Demo\n");
11
12 let config = Config::from_file("config.toml")?;
13
14 // Create a simpler forest with just 3 agents
15 let mut forest = ForestBuilder::new()
16 .config(config)
17 .agent(
18 "coordinator".to_string(),
19 Agent::builder("coordinator")
20 .system_prompt(
21 "You are a project coordinator. Your ONLY job is to create plans, not execute tasks.\n\
22 When given a task, IMMEDIATELY use the create_plan tool with this format:\n\
23 - objective: the overall goal\n\
24 - tasks: JSON array with structure [{\"id\":\"task_1\",\"description\":\"...\",\"assigned_to\":\"worker1\",\"dependencies\":[]}]\n\n\
25 Keep plans simple with 2-3 tasks max. Do NOT try to complete the task yourself."
26 )
27 .max_iterations(15)
28 )
29 .agent(
30 "worker1".to_string(),
31 Agent::builder("worker1")
32 .system_prompt(
33 "You are a helpful worker. Complete the task assigned to you and use the \
34 update_task_memory tool to save your results. Be brief and direct."
35 )
36 .max_iterations(8)
37 )
38 .agent(
39 "worker2".to_string(),
40 Agent::builder("worker2")
41 .system_prompt(
42 "You are a helpful worker. Complete the task assigned to you and use the \
43 update_task_memory tool to save your results. Be brief and direct."
44 )
45 .max_iterations(8)
46 )
47 .max_iterations(20)
48 .build()
49 .await?;
50
51 println!("✅ Forest created with 3 agents\n");
52
53 // Simple task
54 let task = "List 3 benefits of exercise. Keep it brief.";
55 println!("📋 Task: {}\n", task);
56
57 let result = forest
58 .execute_collaborative_task(
59 &"coordinator".to_string(),
60 task.to_string(),
61 vec!["worker1".to_string(), "worker2".to_string()],
62 )
63 .await?;
64
65 println!("\n{}\n", "=".repeat(60));
66 println!("✨ RESULT:\n{}\n", result);
67 println!("{}\n", "=".repeat(60));
68
69 // Show task breakdown
70 let context = forest.get_shared_context().await;
71 if let Some(plan) = context.get_plan() {
72 println!("📊 Plan Summary:");
73 let (completed, total) = plan.get_progress();
74 println!(" Completed: {}/{} tasks\n", completed, total);
75
76 for task in plan.tasks_in_order() {
77 let status = match task.status {
78 helios_engine::forest::TaskStatus::Completed => "✅",
79 helios_engine::forest::TaskStatus::InProgress => "🔄",
80 helios_engine::forest::TaskStatus::Pending => "⏳",
81 helios_engine::forest::TaskStatus::Failed => "❌",
82 };
83 println!(" {} [{}] {}", status, task.assigned_to, task.description);
84 }
85 } else {
86 println!("📊 No plan was created (coordinator handled directly)");
87 }
88
89 println!("\n✅ Demo completed!");
90
91 Ok(())
92}More examples
examples/forest_of_agents.rs (line 203)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}examples/forest_with_coordinator.rs (line 160)
19async fn main() -> helios_engine::Result<()> {
20 println!("🚀 Forest of Agents with Coordinator-Based Planning\n");
21
22 // Load configuration
23 let config = Config::from_file("config.toml")?;
24
25 // Create a Forest of Agents with specialized roles
26 let mut forest = ForestBuilder::new()
27 .config(config)
28 // Coordinator agent - creates plans and manages the team
29 .agent(
30 "coordinator".to_string(),
31 Agent::builder("coordinator")
32 .system_prompt(
33 "You are an expert project coordinator and task planner. Your role is to:\n\
34 1. Analyze complex tasks and break them into manageable subtasks\n\
35 2. Create detailed plans using the 'create_plan' tool\n\
36 3. Assign tasks to the most appropriate team members based on their expertise\n\
37 4. Define task dependencies to ensure proper execution order\n\
38 5. Synthesize final results from all team members\n\n\
39 Available team members:\n\
40 - researcher: Gathers information, conducts analysis, finds data\n\
41 - writer: Creates content, documentation, and written materials\n\
42 - analyst: Analyzes data, identifies patterns, provides insights\n\
43 - reviewer: Reviews work quality, provides feedback, ensures standards\n\n\
44 When creating a plan, think carefully about:\n\
45 - What information is needed first (research/data gathering)\n\
46 - What depends on what (task dependencies)\n\
47 - Who is best suited for each task\n\
48 - How to ensure quality (review steps)\n\n\
49 Always use the create_plan tool to structure the work.",
50 )
51 .max_iterations(20),
52 )
53 // Research agent - gathers information and data
54 .agent(
55 "researcher".to_string(),
56 Agent::builder("researcher")
57 .system_prompt(
58 "You are a research specialist who excels at:\n\
59 - Gathering comprehensive information on topics\n\
60 - Identifying key facts, statistics, and sources\n\
61 - Analyzing information for relevance and accuracy\n\
62 - Providing well-organized research findings\n\n\
63 When completing a task:\n\
64 1. Review the shared memory to see what other agents have done\n\
65 2. Conduct thorough research on your assigned topic\n\
66 3. Use 'update_task_memory' tool to save your findings\n\
67 4. Include key data points that other agents might need\n\n\
68 Be thorough but concise in your responses.",
69 )
70 .max_iterations(10),
71 )
72 // Writer agent - creates content
73 .agent(
74 "writer".to_string(),
75 Agent::builder("writer")
76 .system_prompt(
77 "You are a skilled content writer who excels at:\n\
78 - Creating clear, engaging, and well-structured content\n\
79 - Adapting tone and style to the audience\n\
80 - Incorporating research and data into narratives\n\
81 - Writing comprehensive yet accessible material\n\n\
82 When completing a task:\n\
83 1. Review the shared memory for research and data from other agents\n\
84 2. Create well-structured content based on the requirements\n\
85 3. Use 'update_task_memory' tool to save your written content\n\
86 4. Ensure your content is complete and ready for review\n\n\
87 Write clearly and professionally.",
88 )
89 .max_iterations(10),
90 )
91 // Analyst agent - analyzes data and provides insights
92 .agent(
93 "analyst".to_string(),
94 Agent::builder("analyst")
95 .system_prompt(
96 "You are a data analyst who excels at:\n\
97 - Analyzing information and identifying patterns\n\
98 - Drawing insights from data and research\n\
99 - Providing actionable recommendations\n\
100 - Summarizing complex information clearly\n\n\
101 When completing a task:\n\
102 1. Review the shared memory for available data and research\n\
103 2. Analyze the information thoroughly\n\
104 3. Use 'update_task_memory' tool to save your analysis and insights\n\
105 4. Provide clear, actionable conclusions\n\n\
106 Be analytical and data-driven in your responses.",
107 )
108 .max_iterations(10),
109 )
110 // Reviewer agent - ensures quality
111 .agent(
112 "reviewer".to_string(),
113 Agent::builder("reviewer")
114 .system_prompt(
115 "You are a quality reviewer who excels at:\n\
116 - Reviewing content for accuracy and completeness\n\
117 - Identifying areas for improvement\n\
118 - Ensuring consistency and quality standards\n\
119 - Providing constructive feedback\n\n\
120 When completing a task:\n\
121 1. Review the shared memory to see all completed work\n\
122 2. Evaluate the quality, accuracy, and completeness\n\
123 3. Use 'update_task_memory' tool to save your review and any improvements\n\
124 4. Provide clear assessment and final approval\n\n\
125 Be thorough and constructive in your reviews.",
126 )
127 .max_iterations(15),
128 )
129 .max_iterations(30)
130 .build()
131 .await?;
132
133 println!("✅ Forest created with 5 specialized agents\n");
134
135 let task1 = "Create a comprehensive guide about the benefits of renewable energy. \
136 Include research-backed information, clear explanations, data analysis, \
137 and ensure it's well-reviewed for quality.";
138
139 println!("📋 Task: {}\n", task1);
140
141 let result1 = forest
142 .execute_collaborative_task(
143 &"coordinator".to_string(),
144 task1.to_string(),
145 vec![
146 "researcher".to_string(),
147 "writer".to_string(),
148 "analyst".to_string(),
149 "reviewer".to_string(),
150 ],
151 )
152 .await?;
153
154 println!("\n{}\n", "=".repeat(70));
155 println!("✨ FINAL RESULT:\n{}\n", result1);
156 println!("{}\n", "=".repeat(70));
157
158 // Show the shared memory state
159 println!("📊 SHARED MEMORY STATE:");
160 let context = forest.get_shared_context().await;
161
162 if let Some(plan) = context.get_plan() {
163 println!("\n📋 Task Plan Summary:");
164 println!(" Objective: {}", plan.objective);
165 println!(" Total Tasks: {}", plan.tasks.len());
166 println!(
167 " Completed: {}/{}",
168 plan.get_progress().0,
169 plan.get_progress().1
170 );
171 println!("\n Task Breakdown:");
172 for task in plan.tasks_in_order() {
173 let status_icon = match task.status {
174 helios_engine::forest::TaskStatus::Completed => "✅",
175 helios_engine::forest::TaskStatus::InProgress => "🔄",
176 helios_engine::forest::TaskStatus::Pending => "⏳",
177 helios_engine::forest::TaskStatus::Failed => "❌",
178 };
179 println!(
180 " {} [{}] {} - {}",
181 status_icon, task.assigned_to, task.id, task.description
182 );
183 if let Some(result) = &task.result {
184 let preview = if result.len() > 100 {
185 format!("{}...", &result[..100])
186 } else {
187 result.clone()
188 };
189 println!(" Result: {}", preview);
190 }
191 }
192 }
193
194 println!("\n Shared Data Keys:");
195 for key in context.data.keys() {
196 if !key.starts_with("current_")
197 && !key.starts_with("involved_")
198 && !key.starts_with("task_status")
199 {
200 println!(" • {}", key);
201 }
202 }
203
204 println!("\n✅ Demo completed successfully!");
205
206 Ok(())
207}Sets a value in the shared context.
Examples found in repository?
examples/forest_of_agents.rs (lines 192-200)
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 // Using the improved syntax to add multiple agents at once!
29 let mut forest = ForestBuilder::new()
30 .config(config)
31 .agents(vec![
32 // Coordinator agent - manages the team and delegates tasks
33 (
34 "coordinator".to_string(),
35 Agent::builder("coordinator")
36 .system_prompt(
37 "You are a project coordinator. For simple tasks that you can handle yourself, \
38 complete them directly and provide a complete response. For complex tasks that \
39 require specialized expertise, you can delegate using the 'delegate_task' tool \
40 to agents like 'researcher', 'writer', 'editor', and 'qa'.\n\n\
41 When you delegate a task, WAIT for the response and then synthesize the results. \
42 Always provide a final, complete answer to the user's request."
43 )
44 .max_iterations(10)
45 ),
46 // Research agent - gathers and analyzes information
47 (
48 "researcher".to_string(),
49 Agent::builder("researcher")
50 .system_prompt(
51 "You are a research specialist who excels at gathering information, \
52 analyzing data, and providing insights. You work closely with the coordinator \
53 and writer to ensure all work is based on accurate information. Use \
54 communication tools to share your findings and request clarification when needed."
55 )
56 .max_iterations(10)
57 ),
58 // Writer agent - creates content and documentation
59 (
60 "writer".to_string(),
61 Agent::builder("writer")
62 .system_prompt(
63 "You are a skilled writer who creates clear, well-structured content and \
64 documentation. When you receive a task, complete it fully and provide the \
65 final written content. You can use communication tools to request information \
66 from the researcher if needed."
67 )
68 .max_iterations(10)
69 ),
70 // Editor agent - reviews and improves content
71 (
72 "editor".to_string(),
73 Agent::builder("editor")
74 .system_prompt(
75 "You are an editor who reviews content for quality, clarity, and consistency. \
76 When you receive content to review, provide constructive feedback and an \
77 improved version."
78 )
79 .max_iterations(10)
80 ),
81 // Quality Assurance agent - validates the final output
82 (
83 "qa".to_string(),
84 Agent::builder("qa")
85 .system_prompt(
86 "You are a quality assurance specialist who validates that all requirements \
87 are met and the output is accurate and complete. When you receive content to \
88 review, verify it meets all requirements and provide your assessment."
89 )
90 .max_iterations(10)
91 ),
92 ])
93 .max_iterations(15)
94 .build()
95 .await?;
96
97 println!("✅ Created Forest of Agents with 5 specialized agents:");
98 println!(" • 🎯 Coordinator: Manages projects and delegates tasks");
99 println!(" • 🔬 Researcher: Gathers and analyzes information");
100 println!(" • ✍️ Writer: Creates content and documentation");
101 println!(" • 📝 Editor: Reviews and improves content quality");
102 println!(" • ✅ QA: Validates requirements and final output");
103 println!();
104
105 // Demonstrate collaborative task execution with streaming
106 println!("🎯 TASK: Create a brief guide on sustainable gardening");
107 println!("{}", "=".repeat(70));
108 println!();
109
110 println!("🎬 Starting collaborative task execution...");
111 println!(" (Watch the responses stream in real-time!)\n");
112
113 // Simpler task for demonstration - DISABLED TOOLS FOR TESTING
114 let task = "Create a brief guide (2-3 paragraphs) on sustainable gardening. \
115 Include key benefits and one practical technique.";
116
117 println!("📋 Task Description:");
118 println!(" {}\n", task);
119
120 println!("{}", "─".repeat(70));
121 println!("🤖 COORDINATOR (streaming response):");
122 print!(" ");
123 io::stdout().flush()?;
124
125 let _result = forest
126 .execute_collaborative_task(
127 &"coordinator".to_string(),
128 task.to_string(),
129 vec![
130 "researcher".to_string(),
131 "writer".to_string(),
132 "editor".to_string(),
133 "qa".to_string(),
134 ],
135 )
136 .await?;
137
138 println!();
139 println!("{}", "─".repeat(70));
140 println!();
141 println!("✨ Collaborative task completed!");
142 println!();
143
144 // Demonstrate direct agent communication with streaming
145 println!("💬 Testing direct agent-to-agent communication with streaming:");
146 println!("{}", "─".repeat(70));
147 println!();
148
149 let mut forest_clone = forest;
150
151 // Test a simple chat to show streaming
152 println!("📤 Sending task to Writer agent...");
153 println!("🤖 WRITER (streaming response):");
154 print!(" ");
155 io::stdout().flush()?;
156
157 if let Some(writer) = forest_clone.get_agent_mut(&"writer".to_string()) {
158 let _response = writer
159 .chat("Write one short paragraph about composting.")
160 .await?;
161 println!();
162 }
163
164 println!();
165 println!("{}", "─".repeat(70));
166 println!();
167
168 // Send a direct message between agents
169 println!("📤 Coordinator → Researcher: Direct message");
170 forest_clone
171 .send_message(
172 &"coordinator".to_string(),
173 Some(&"researcher".to_string()),
174 "Great job on the research! The information was very helpful.".to_string(),
175 )
176 .await?;
177
178 forest_clone.process_messages().await?;
179
180 if let Some(researcher) = forest_clone.get_agent(&"researcher".to_string()) {
181 let messages = researcher.chat_session().messages.clone();
182 if let Some(last_msg) = messages.last() {
183 println!("📥 Researcher received: \"{}\"", last_msg.content);
184 }
185 }
186 println!();
187
188 // Demonstrate shared context
189 println!("🧠 Shared Context Demo:");
190 println!("{}", "─".repeat(70));
191 forest_clone
192 .set_shared_context(
193 "project_status".to_string(),
194 serde_json::json!({
195 "name": "Sustainable Gardening Guide",
196 "status": "completed",
197 "contributors": ["coordinator", "researcher", "writer"],
198 "completion_date": "2025-11-03"
199 }),
200 )
201 .await;
202
203 let context = forest_clone.get_shared_context().await;
204 if let Some(status) = context.get("project_status") {
205 println!("📊 Shared project status:");
206 println!("{}", serde_json::to_string_pretty(&status).unwrap());
207 }
208 println!();
209
210 println!("{}", "=".repeat(70));
211 println!("✅ Forest of Agents Demo Completed Successfully!");
212 println!("{}", "=".repeat(70));
213 println!();
214 println!("🎉 Key Features Demonstrated:");
215 println!(" ✓ Real-time streaming responses from all agents");
216 println!(" ✓ Multi-agent collaboration on tasks");
217 println!(" ✓ Inter-agent communication (direct messages)");
218 println!(" ✓ Task delegation and coordination");
219 println!(" ✓ Shared context and memory");
220 println!(" ✓ Specialized agent roles working together");
221 println!();
222 println!("💡 Notice how all responses streamed token-by-token in real-time!");
223 println!(" This provides immediate feedback and better user experience.");
224
225 Ok(())
226}Trait Implementations§
Auto Trait Implementations§
impl Freeze for ForestOfAgents
impl !RefUnwindSafe for ForestOfAgents
impl Send for ForestOfAgents
impl Sync for ForestOfAgents
impl Unpin for ForestOfAgents
impl !UnwindSafe for ForestOfAgents
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more