mojentic/examples/react/
thinking_agent.rs1use 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 std::sync::Arc;
13
14use super::events::{FailureOccurred, InvokeDecisioning, InvokeThinking};
15use super::formatters::{format_available_tools, format_current_context};
16use super::models::{Plan, ThoughtActionObservation};
17
18pub struct ThinkingAgent {
23 llm: Arc<LlmBroker>,
24 tools: Vec<Box<dyn LlmTool>>,
25}
26
27impl ThinkingAgent {
28 pub fn new(llm: Arc<LlmBroker>) -> Self {
34 Self {
35 llm,
36 tools: vec![Box::new(SimpleDateTool)],
37 }
38 }
39
40 fn prompt(&self, event: &InvokeThinking) -> String {
42 let tools_list: Vec<&dyn LlmTool> = self.tools.iter().map(|t| t.as_ref()).collect();
43
44 format!(
45 "You are to solve a problem by reasoning and acting on the information you have. Here is the current context:
46
47{}
48{}
49
50Your Instructions:
51Given our context and what we've done so far, and the tools available, create a step-by-step plan to answer the query.
52Each step should be concrete and actionable. Consider which tools you'll need to use.",
53 format_current_context(&event.context),
54 format_available_tools(&tools_list)
55 )
56 }
57}
58
59#[async_trait]
60impl BaseAsyncAgent for ThinkingAgent {
61 async fn receive_event_async(&self, event: Box<dyn Event>) -> Result<Vec<Box<dyn Event>>> {
62 let thinking_event = match event.as_any().downcast_ref::<InvokeThinking>() {
64 Some(e) => e,
65 None => return Ok(vec![]),
66 };
67
68 let prompt = self.prompt(thinking_event);
69 println!("\n{}\n{}\n{}\n", "=".repeat(80), prompt, "=".repeat(80));
70
71 let plan = match self
73 .llm
74 .generate_object::<Plan>(
75 &[LlmMessage {
76 role: MessageRole::User,
77 content: Some(prompt),
78 tool_calls: None,
79 image_paths: None,
80 reasoning_content: None,
81 }],
82 None,
83 thinking_event.correlation_id.clone(),
84 )
85 .await
86 {
87 Ok(p) => p,
88 Err(e) => {
89 return Ok(vec![Box::new(FailureOccurred {
90 source: "ThinkingAgent".to_string(),
91 correlation_id: thinking_event.correlation_id.clone(),
92 context: thinking_event.context.clone(),
93 reason: format!("Error during planning: {}", e),
94 }) as Box<dyn Event>]);
95 }
96 };
97
98 println!("\n{}\nPlan: {:?}\n{}\n", "=".repeat(80), plan, "=".repeat(80));
99
100 let mut updated_context = thinking_event.context.clone();
102 updated_context.plan = plan.clone();
103
104 updated_context.history.push(ThoughtActionObservation {
106 thought: "I need to create a plan to solve this query.".to_string(),
107 action: "Created a step-by-step plan.".to_string(),
108 observation: format!("Plan has {} steps.", plan.steps.len()),
109 });
110
111 Ok(vec![Box::new(InvokeDecisioning {
112 source: "ThinkingAgent".to_string(),
113 correlation_id: thinking_event.correlation_id.clone(),
114 context: updated_context,
115 }) as Box<dyn Event>])
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122 use crate::llm::gateways::OllamaGateway;
123
124 use super::super::models::CurrentContext;
125
126 #[test]
127 fn test_thinking_agent_prompt_generation() {
128 let gateway = Arc::new(OllamaGateway::new());
129 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
130 let agent = ThinkingAgent::new(llm);
131
132 let context = CurrentContext::new("What is the date tomorrow?");
133 let event = InvokeThinking {
134 source: "TestSource".to_string(),
135 correlation_id: Some("test-123".to_string()),
136 context,
137 };
138
139 let prompt = agent.prompt(&event);
140
141 assert!(prompt.contains("What is the date tomorrow?"));
142 assert!(prompt.contains("create a step-by-step plan"));
143 assert!(prompt.contains("resolve_date"));
144 }
145
146 #[test]
147 fn test_thinking_agent_with_existing_plan() {
148 let gateway = Arc::new(OllamaGateway::new());
149 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
150 let agent = ThinkingAgent::new(llm);
151
152 let mut context = CurrentContext::new("What day is it?");
153 context.plan = Plan {
154 steps: vec!["Get current date".to_string()],
155 };
156
157 let event = InvokeThinking {
158 source: "TestSource".to_string(),
159 correlation_id: Some("test-456".to_string()),
160 context,
161 };
162
163 let prompt = agent.prompt(&event);
164
165 assert!(prompt.contains("Current plan:"));
166 assert!(prompt.contains("Get current date"));
167 }
168
169 #[tokio::test]
170 async fn test_thinking_agent_ignores_wrong_event_type() {
171 let gateway = Arc::new(OllamaGateway::new());
172 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
173 let agent = ThinkingAgent::new(llm);
174
175 let wrong_event = Box::new(InvokeDecisioning {
176 source: "Wrong".to_string(),
177 correlation_id: None,
178 context: CurrentContext::new("Test"),
179 }) as Box<dyn Event>;
180
181 let result = agent.receive_event_async(wrong_event).await.unwrap();
182 assert!(result.is_empty());
183 }
184}