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