mojentic/examples/react/
summarization_agent.rs1use crate::agents::BaseAsyncAgent;
6use crate::event::Event;
7use crate::llm::{LlmBroker, LlmMessage, MessageRole};
8use crate::Result;
9use async_trait::async_trait;
10use std::sync::Arc;
11
12use super::events::{FailureOccurred, FinishAndSummarize};
13use super::formatters::format_current_context;
14
15pub struct SummarizationAgent {
20 llm: Arc<LlmBroker>,
21}
22
23impl SummarizationAgent {
24 pub fn new(llm: Arc<LlmBroker>) -> Self {
30 Self { llm }
31 }
32
33 fn prompt(&self, event: &FinishAndSummarize) -> String {
35 format!(
36 "Based on the following context, provide a clear and concise answer to the user's query.
37
38{}
39
40Your task:
41Review what we've learned and provide a direct answer to: \"{}\"
42
43Be specific and use the information gathered during our process.",
44 format_current_context(&event.context),
45 event.context.user_query
46 )
47 }
48}
49
50#[async_trait]
51impl BaseAsyncAgent for SummarizationAgent {
52 async fn receive_event_async(&self, event: Box<dyn Event>) -> Result<Vec<Box<dyn Event>>> {
53 let finish_event = match event.as_any().downcast_ref::<FinishAndSummarize>() {
55 Some(e) => e,
56 None => return Ok(vec![]),
57 };
58
59 let prompt = self.prompt(finish_event);
60 println!("\n{}\n{}\n{}\n", "=".repeat(80), prompt, "=".repeat(80));
61
62 let response = match self
64 .llm
65 .generate(
66 &[LlmMessage {
67 role: MessageRole::User,
68 content: Some(prompt),
69 tool_calls: None,
70 image_paths: None,
71 reasoning_content: None,
72 }],
73 None,
74 None,
75 finish_event.correlation_id.clone(),
76 )
77 .await
78 {
79 Ok(r) => r,
80 Err(e) => {
81 return Ok(vec![Box::new(FailureOccurred {
82 source: "SummarizationAgent".to_string(),
83 correlation_id: finish_event.correlation_id.clone(),
84 context: finish_event.context.clone(),
85 reason: format!("Error during summarization: {}", e),
86 }) as Box<dyn Event>]);
87 }
88 };
89
90 println!("\n{}", "=".repeat(80));
91 println!("FINAL ANSWER:");
92 println!("{}", "=".repeat(80));
93 println!("{}", response);
94 println!("{}\n", "=".repeat(80));
95
96 Ok(vec![])
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104 use crate::llm::gateways::OllamaGateway;
105
106 use super::super::models::{CurrentContext, Plan, ThoughtActionObservation};
107
108 #[test]
109 fn test_summarization_agent_prompt_generation() {
110 let gateway = Arc::new(OllamaGateway::new());
111 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
112 let agent = SummarizationAgent::new(llm);
113
114 let mut context = CurrentContext::new("What is the date tomorrow?");
115 context.history.push(ThoughtActionObservation {
116 thought: "Need to resolve date".to_string(),
117 action: "Called resolve_date".to_string(),
118 observation: "2025-11-30".to_string(),
119 });
120
121 let event = FinishAndSummarize {
122 source: "TestSource".to_string(),
123 correlation_id: Some("test-123".to_string()),
124 context,
125 thought: "I have the information needed".to_string(),
126 };
127
128 let prompt = agent.prompt(&event);
129
130 assert!(prompt.contains("What is the date tomorrow?"));
131 assert!(prompt.contains("provide a direct answer"));
132 assert!(prompt.contains("2025-11-30"));
133 }
134
135 #[test]
136 fn test_summarization_agent_with_plan() {
137 let gateway = Arc::new(OllamaGateway::new());
138 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
139 let agent = SummarizationAgent::new(llm);
140
141 let mut context = CurrentContext::new("What day is next Friday?");
142 context.plan = Plan {
143 steps: vec!["Resolve date for next Friday".to_string()],
144 };
145 context.history.push(ThoughtActionObservation {
146 thought: "Calculate next Friday".to_string(),
147 action: "Called resolve_date".to_string(),
148 observation: "2025-11-29".to_string(),
149 });
150
151 let event = FinishAndSummarize {
152 source: "TestSource".to_string(),
153 correlation_id: Some("test-456".to_string()),
154 context,
155 thought: "Ready to summarize".to_string(),
156 };
157
158 let prompt = agent.prompt(&event);
159
160 assert!(prompt.contains("What day is next Friday?"));
161 assert!(prompt.contains("Current plan:"));
162 assert!(prompt.contains("2025-11-29"));
163 }
164
165 #[tokio::test]
166 async fn test_summarization_agent_ignores_wrong_event_type() {
167 let gateway = Arc::new(OllamaGateway::new());
168 let llm = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
169 let agent = SummarizationAgent::new(llm);
170
171 use super::super::events::InvokeThinking;
172
173 let wrong_event = Box::new(InvokeThinking {
174 source: "Wrong".to_string(),
175 correlation_id: None,
176 context: CurrentContext::new("Test"),
177 }) as Box<dyn Event>;
178
179 let result = agent.receive_event_async(wrong_event).await.unwrap();
180 assert!(result.is_empty());
181 }
182}