mojentic/examples/react/
tool_call_agent.rs1use crate::agents::BaseAsyncAgent;
6use crate::event::Event;
7use crate::Result;
8use async_trait::async_trait;
9
10use super::events::{FailureOccurred, InvokeDecisioning, InvokeToolCall};
11use super::models::ThoughtActionObservation;
12
13pub struct ToolCallAgent;
19
20impl ToolCallAgent {
21 pub fn new() -> Self {
23 Self
24 }
25}
26
27impl Default for ToolCallAgent {
28 fn default() -> Self {
29 Self::new()
30 }
31}
32
33#[async_trait]
34impl BaseAsyncAgent for ToolCallAgent {
35 async fn receive_event_async(&self, event: Box<dyn Event>) -> Result<Vec<Box<dyn Event>>> {
36 let tool_call_event = match event.as_any().downcast_ref::<InvokeToolCall>() {
38 Some(e) => e,
39 None => return Ok(vec![]),
40 };
41
42 let tool = &tool_call_event.tool;
43 let tool_name = tool.descriptor().function.name.clone();
44 let arguments = &tool_call_event.tool_arguments;
45
46 println!("\nExecuting tool: {}", tool_name);
47 println!("Arguments: {:?}", arguments);
48
49 let ctx = crate::llm::tools::ToolRunCtx::default();
51 let result = match tool.run(arguments, &ctx).await {
52 Ok(r) => r,
53 Err(e) => {
54 eprintln!("Tool execution error: {}", e);
55 return Ok(vec![Box::new(FailureOccurred {
56 source: "ToolCallAgent".to_string(),
57 correlation_id: tool_call_event.correlation_id.clone(),
58 context: tool_call_event.context.clone(),
59 reason: format!("Tool execution failed: {}", e),
60 }) as Box<dyn Event>]);
61 }
62 };
63
64 println!("Result: {:?}", result);
65
66 let result_text = if result.is_object() {
68 result
70 .get("summary")
71 .and_then(|v| v.as_str())
72 .map(|s| s.to_string())
73 .unwrap_or_else(|| result.to_string())
74 } else {
75 result.to_string()
76 };
77
78 let mut updated_context = tool_call_event.context.clone();
80 updated_context.history.push(ThoughtActionObservation {
81 thought: tool_call_event.thought.clone(),
82 action: format!("Called {} with {:?}", tool_name, tool_call_event.tool_arguments),
83 observation: result_text,
84 });
85
86 Ok(vec![Box::new(InvokeDecisioning {
88 source: "ToolCallAgent".to_string(),
89 correlation_id: tool_call_event.correlation_id.clone(),
90 context: updated_context,
91 }) as Box<dyn Event>])
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98 use crate::llm::tools::simple_date_tool::SimpleDateTool;
99 use crate::llm::tools::LlmTool;
100 use serde_json::json;
101 use std::collections::HashMap;
102 use std::sync::Arc;
103
104 use super::super::events::InvokeToolCall;
105 use super::super::models::{CurrentContext, NextAction};
106
107 #[tokio::test]
108 async fn test_tool_call_agent_successful_execution() {
109 let agent = ToolCallAgent::new();
110 let tool: Arc<dyn LlmTool> = Arc::new(SimpleDateTool);
111
112 let mut args = HashMap::new();
113 args.insert("relative_date".to_string(), json!("tomorrow"));
114
115 let context = CurrentContext::new("What is the date tomorrow?");
116
117 let event = Box::new(InvokeToolCall {
118 source: "TestSource".to_string(),
119 correlation_id: Some("test-123".to_string()),
120 context,
121 thought: "I need to resolve the date".to_string(),
122 action: NextAction::Act,
123 tool,
124 tool_arguments: args,
125 }) as Box<dyn Event>;
126
127 let result = agent.receive_event_async(event).await.unwrap();
128 assert_eq!(result.len(), 1);
129
130 let decisioning = result[0].as_any().downcast_ref::<InvokeDecisioning>();
132 assert!(decisioning.is_some());
133
134 let decisioning = decisioning.unwrap();
135 assert_eq!(decisioning.context.history.len(), 1);
136 assert!(decisioning.context.history[0].observation.contains("tomorrow"));
137 }
138
139 #[tokio::test]
140 async fn test_tool_call_agent_ignores_wrong_event_type() {
141 let agent = ToolCallAgent::new();
142
143 let wrong_event = Box::new(InvokeDecisioning {
144 source: "Wrong".to_string(),
145 correlation_id: None,
146 context: CurrentContext::new("Test"),
147 }) as Box<dyn Event>;
148
149 let result = agent.receive_event_async(wrong_event).await.unwrap();
150 assert!(result.is_empty());
151 }
152
153 #[test]
154 fn test_tool_call_agent_default() {
155 let _agent1 = ToolCallAgent::new();
156 let _agent2 = ToolCallAgent;
157 }
158}