Skip to main content

mojentic/examples/react/
decisioning_agent.rs

1//! Decision-making agent for the ReAct pattern.
2//!
3//! This agent evaluates the current context and decides on the next action to take.
4
5use crate::agents::BaseAsyncAgent;
6use crate::event::Event;
7use crate::llm::tools::simple_date_tool::SimpleDateTool;
8use crate::llm::tools::LlmTool;
9use crate::llm::{LlmBroker, LlmMessage, MessageRole};
10use crate::Result;
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::Arc;
15
16use super::events::{
17    FailureOccurred, FinishAndSummarize, InvokeDecisioning, InvokeThinking, InvokeToolCall,
18};
19use super::formatters::{format_available_tools, format_current_context};
20use super::models::NextAction;
21
22/// Structured response from the decisioning agent.
23#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
24pub struct DecisionResponse {
25    /// The reasoning behind the decision
26    pub thought: String,
27    /// What should happen next: PLAN, ACT, or FINISH
28    pub next_action: NextAction,
29    /// Name of tool to use if next_action is ACT
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub tool_name: Option<String>,
32    /// Arguments for the tool if next_action is ACT
33    #[serde(default)]
34    pub tool_arguments: HashMap<String, serde_json::Value>,
35}
36
37/// Agent responsible for deciding the next action in the ReAct loop.
38///
39/// This agent evaluates the current context, plan, and history to determine
40/// whether to continue planning, take an action, or finish and summarize.
41pub struct DecisioningAgent {
42    llm: Arc<LlmBroker>,
43    tools: Vec<Arc<dyn LlmTool>>,
44}
45
46impl DecisioningAgent {
47    /// Maximum iterations before failing
48    const MAX_ITERATIONS: usize = 10;
49
50    /// Initialize the decisioning agent.
51    ///
52    /// # Arguments
53    ///
54    /// * `llm` - The LLM broker to use for generating decisions.
55    pub fn new(llm: Arc<LlmBroker>) -> Self {
56        Self {
57            llm,
58            tools: vec![Arc::new(SimpleDateTool)],
59        }
60    }
61
62    /// Generate the prompt for the decision-making LLM.
63    fn prompt(&self, event: &InvokeDecisioning) -> String {
64        let tools_list: Vec<&dyn LlmTool> = self.tools.iter().map(|t| t.as_ref()).collect();
65
66        format!(
67            "You are to solve a problem by reasoning and acting on the information you have. Here is the current context:
68
69{}
70{}
71
72Your Instructions:
73Review the current plan and history. Decide what to do next:
74
751. PLAN - If the plan is incomplete or needs refinement
762. ACT - If you should take an action using one of the available tools
773. FINISH - If you have enough information to answer the user's query
78
79If you choose ACT, specify which tool to use and what arguments to pass.
80Think carefully about whether each step in the plan has been completed.",
81            format_current_context(&event.context),
82            format_available_tools(&tools_list)
83        )
84    }
85}
86
87#[async_trait]
88impl BaseAsyncAgent for DecisioningAgent {
89    async fn receive_event_async(&self, event: Box<dyn Event>) -> Result<Vec<Box<dyn Event>>> {
90        // Downcast to InvokeDecisioning
91        let decisioning_event = match event.as_any().downcast_ref::<InvokeDecisioning>() {
92            Some(e) => e,
93            None => return Ok(vec![]),
94        };
95
96        // Check iteration limit
97        if decisioning_event.context.iteration >= Self::MAX_ITERATIONS {
98            return Ok(vec![Box::new(FailureOccurred {
99                source: "DecisioningAgent".to_string(),
100                correlation_id: decisioning_event.correlation_id.clone(),
101                context: decisioning_event.context.clone(),
102                reason: format!("Maximum iterations ({}) exceeded", Self::MAX_ITERATIONS),
103            }) as Box<dyn Event>]);
104        }
105
106        // Increment iteration counter
107        let mut updated_context = decisioning_event.context.clone();
108        updated_context.iteration += 1;
109
110        let prompt = self.prompt(decisioning_event);
111        println!("\n{}\n{}\n{}\n", "=".repeat(80), prompt, "=".repeat(80));
112
113        // Generate decision using structured output
114        let decision = match self
115            .llm
116            .generate_object::<DecisionResponse>(
117                &[LlmMessage {
118                    role: MessageRole::User,
119                    content: Some(prompt),
120                    tool_calls: None,
121                    image_paths: None,
122                    reasoning_content: None,
123                }],
124                None,
125                decisioning_event.correlation_id.clone(),
126            )
127            .await
128        {
129            Ok(d) => d,
130            Err(e) => {
131                return Ok(vec![Box::new(FailureOccurred {
132                    source: "DecisioningAgent".to_string(),
133                    correlation_id: decisioning_event.correlation_id.clone(),
134                    context: updated_context,
135                    reason: format!("Error during decision making: {}", e),
136                }) as Box<dyn Event>]);
137            }
138        };
139
140        println!("\n{}\nDecision: {:?}\n{}\n", "=".repeat(80), decision, "=".repeat(80));
141
142        // Route based on decision
143        match decision.next_action {
144            NextAction::Finish => Ok(vec![Box::new(FinishAndSummarize {
145                source: "DecisioningAgent".to_string(),
146                correlation_id: decisioning_event.correlation_id.clone(),
147                context: updated_context,
148                thought: decision.thought,
149            }) as Box<dyn Event>]),
150
151            NextAction::Act => {
152                let tool_name = match decision.tool_name {
153                    Some(name) => name,
154                    None => {
155                        return Ok(vec![Box::new(FailureOccurred {
156                            source: "DecisioningAgent".to_string(),
157                            correlation_id: decisioning_event.correlation_id.clone(),
158                            context: updated_context,
159                            reason: "ACT decision made but no tool specified".to_string(),
160                        }) as Box<dyn Event>]);
161                    }
162                };
163
164                // Find the requested tool
165                let tool =
166                    match self.tools.iter().find(|t| t.descriptor().function.name == tool_name) {
167                        Some(t) => t.clone(),
168                        None => {
169                            return Ok(vec![Box::new(FailureOccurred {
170                                source: "DecisioningAgent".to_string(),
171                                correlation_id: decisioning_event.correlation_id.clone(),
172                                context: updated_context,
173                                reason: format!("Tool '{}' not found", tool_name),
174                            }) as Box<dyn Event>]);
175                        }
176                    };
177
178                Ok(vec![Box::new(InvokeToolCall {
179                    source: "DecisioningAgent".to_string(),
180                    correlation_id: decisioning_event.correlation_id.clone(),
181                    context: updated_context,
182                    thought: decision.thought,
183                    action: NextAction::Act,
184                    tool,
185                    tool_arguments: decision.tool_arguments,
186                }) as Box<dyn Event>])
187            }
188
189            NextAction::Plan => Ok(vec![Box::new(InvokeThinking {
190                source: "DecisioningAgent".to_string(),
191                correlation_id: decisioning_event.correlation_id.clone(),
192                context: updated_context,
193            }) as Box<dyn Event>]),
194        }
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use crate::llm::gateways::OllamaGateway;
202
203    use super::super::models::{CurrentContext, Plan};
204
205    #[test]
206    fn test_decisioning_agent_prompt_generation() {
207        let gateway = Arc::new(OllamaGateway::new());
208        let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
209        let agent = DecisioningAgent::new(llm);
210
211        let context = CurrentContext::new("What is the date tomorrow?");
212        let event = InvokeDecisioning {
213            source: "TestSource".to_string(),
214            correlation_id: Some("test-123".to_string()),
215            context,
216        };
217
218        let prompt = agent.prompt(&event);
219
220        assert!(prompt.contains("What is the date tomorrow?"));
221        assert!(prompt.contains("Decide what to do next"));
222        assert!(prompt.contains("PLAN"));
223        assert!(prompt.contains("ACT"));
224        assert!(prompt.contains("FINISH"));
225    }
226
227    #[test]
228    fn test_decisioning_agent_with_plan() {
229        let gateway = Arc::new(OllamaGateway::new());
230        let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
231        let agent = DecisioningAgent::new(llm);
232
233        let mut context = CurrentContext::new("What day is it?");
234        context.plan = Plan {
235            steps: vec!["Call resolve_date tool".to_string()],
236        };
237
238        let event = InvokeDecisioning {
239            source: "TestSource".to_string(),
240            correlation_id: Some("test-456".to_string()),
241            context,
242        };
243
244        let prompt = agent.prompt(&event);
245
246        assert!(prompt.contains("Current plan:"));
247        assert!(prompt.contains("Call resolve_date tool"));
248    }
249
250    #[tokio::test]
251    async fn test_decisioning_agent_max_iterations() {
252        let gateway = Arc::new(OllamaGateway::new());
253        let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
254        let agent = DecisioningAgent::new(llm);
255
256        let mut context = CurrentContext::new("Test query");
257        context.iteration = DecisioningAgent::MAX_ITERATIONS;
258
259        let event = Box::new(InvokeDecisioning {
260            source: "TestSource".to_string(),
261            correlation_id: Some("test-max".to_string()),
262            context,
263        }) as Box<dyn Event>;
264
265        let result = agent.receive_event_async(event).await.unwrap();
266        assert_eq!(result.len(), 1);
267
268        let failure = result[0].as_any().downcast_ref::<FailureOccurred>().unwrap();
269        assert!(failure.reason.contains("Maximum iterations"));
270    }
271
272    #[tokio::test]
273    async fn test_decisioning_agent_ignores_wrong_event_type() {
274        let gateway = Arc::new(OllamaGateway::new());
275        let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
276        let agent = DecisioningAgent::new(llm);
277
278        let wrong_event = Box::new(InvokeThinking {
279            source: "Wrong".to_string(),
280            correlation_id: None,
281            context: CurrentContext::new("Test"),
282        }) as Box<dyn Event>;
283
284        let result = agent.receive_event_async(wrong_event).await.unwrap();
285        assert!(result.is_empty());
286    }
287}