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