SendMessageTool

Struct SendMessageTool 

Source
pub struct SendMessageTool { /* private fields */ }
Expand description

A tool that allows agents to send messages to other agents.

Implementations§

Source§

impl SendMessageTool

Source

pub fn new( agent_id: AgentId, message_queue: Arc<RwLock<Vec<ForestMessage>>>, shared_context: Arc<RwLock<SharedContext>>, ) -> Self

Creates a new SendMessageTool.

Examples found in repository?
examples/send_message_tool_demo.rs (lines 55-59)
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§

impl Tool for SendMessageTool

Source§

fn name(&self) -> &str

The name of the tool.
Source§

fn description(&self) -> &str

A description of the tool.
Source§

fn parameters(&self) -> HashMap<String, ToolParameter>

The parameters for the tool.
Source§

fn execute<'life0, 'async_trait>( &'life0 self, args: Value, ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Executes the tool with the given arguments.
Source§

fn to_definition(&self) -> ToolDefinition

Converts the tool to a ToolDefinition.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more