adk_core/
event_summarizer.rs1use crate::intra_compaction::render_part_for_summary as render_part;
8use crate::{
9 AdkError, BaseEventsSummarizer, Content, ErrorCategory, ErrorComponent, Event, EventActions,
10 EventCompaction, FinishReason, Llm, LlmRequest, Part, Result,
11};
12use async_trait::async_trait;
13use std::sync::Arc;
14
15const DEFAULT_PROMPT_TEMPLATE: &str = "\
16The following is a conversation history between a user and an AI agent. \
17Please summarize the conversation, focusing on key information and decisions made, \
18as well as any unresolved questions or tasks. \
19The summary should be concise and capture the essence of the interaction.\n\n\
20{conversation_history}";
21
22pub struct LlmEventSummarizer {
46 llm: Arc<dyn Llm>,
47 prompt_template: String,
48}
49
50impl LlmEventSummarizer {
51 pub fn new(llm: Arc<dyn Llm>) -> Self {
53 Self { llm, prompt_template: DEFAULT_PROMPT_TEMPLATE.to_string() }
54 }
55
56 pub fn with_prompt_template(mut self, template: impl Into<String>) -> Self {
59 self.prompt_template = template.into();
60 self
61 }
62
63 fn format_events_for_prompt(events: &[Event], earlier: Option<&EventCompaction>) -> String {
66 let mut lines: Vec<String> = earlier
67 .into_iter()
68 .flat_map(|compaction| compaction.compacted_content.parts.iter())
69 .filter_map(render_part)
70 .map(|summary| format!("summary of earlier conversation: {summary}"))
71 .collect();
72 for event in events {
73 let covered = earlier.is_some_and(|c| event.timestamp <= c.end_timestamp);
74 if event.actions.compaction.is_some() || event.llm_response.partial || covered {
75 continue;
76 }
77 if let Some(content) = &event.llm_response.content {
78 for rendered in content.parts.iter().filter_map(render_part) {
79 lines.push(format!("{}: {rendered}", event.author));
80 }
81 }
82 }
83 lines.join("\n")
84 }
85}
86
87#[async_trait]
88impl BaseEventsSummarizer for LlmEventSummarizer {
89 async fn summarize_events(&self, events: &[Event]) -> Result<Option<Event>> {
90 if events.is_empty() {
91 return Ok(None);
92 }
93
94 let earlier = events.iter().rev().find_map(|event| event.actions.compaction.as_ref());
95 let conversation_history = Self::format_events_for_prompt(events, earlier);
96 let prompt = self.prompt_template.replace("{conversation_history}", &conversation_history);
97
98 let request = LlmRequest {
99 model: self.llm.name().to_string(),
100 contents: vec![Content {
101 role: "user".to_string(),
102 parts: vec![Part::Text { text: prompt }],
103 }],
104 tools: Default::default(),
105 config: None,
106 previous_response_id: None,
107 };
108
109 let mut response_stream =
111 crate::generate_metered(self.llm.as_ref(), request, false).await?;
112
113 use futures::StreamExt;
114 let mut summary_text = String::new();
115 let mut finish_reason = None;
116 while let Some(chunk) = response_stream.next().await {
118 let chunk = chunk.map_err(|cause| {
119 let mut details = (*cause.details).clone();
120 details.metadata.insert("cause_code".to_string(), cause.code.into());
121 AdkError::new(
122 ErrorComponent::Model,
123 cause.category,
124 "model.summary_incomplete",
125 format!(
126 "the summarizer model failed before finishing its summary ({}); the \
127 history is kept as it is",
128 cause.message
129 ),
130 )
131 .with_retry(cause.retry.clone())
132 .with_details(details)
133 .with_source(cause)
134 })?;
135 for part in chunk.content.iter().flat_map(|content| content.parts.iter()) {
136 if let Part::Text { text } = part {
137 summary_text.push_str(text);
138 }
139 }
140 finish_reason = chunk.finish_reason.or(finish_reason);
141 }
142
143 if let Some(reason) = finish_reason.filter(|reason| *reason != FinishReason::Stop) {
146 return Err(AdkError::new(
147 ErrorComponent::Model,
148 ErrorCategory::Internal,
149 "model.summary_incomplete",
150 format!(
151 "the summarizer model stopped before finishing its summary ({reason:?}); \
152 the history is kept as it is. Raise the summarizer's output limit or \
153 shorten the compaction window"
154 ),
155 ));
156 }
157 if summary_text.trim().is_empty() {
158 return Ok(None);
159 }
160 if summary_text.len() >= conversation_history.len() {
162 tracing::debug!(
163 summary.chars = summary_text.len(),
164 window.chars = conversation_history.len(),
165 "summary is not smaller than the history it replaces; skipping compaction"
166 );
167 return Ok(None);
168 }
169 let summary = Content::new("model").with_text(summary_text);
170
171 let start_timestamp = events
173 .first()
174 .map(|e| e.timestamp)
175 .into_iter()
176 .chain(earlier.map(|compaction| compaction.start_timestamp))
177 .min()
178 .unwrap_or_default();
179 let end_timestamp = events.last().map(|e| e.timestamp).unwrap_or_default();
180
181 let compaction =
182 EventCompaction { start_timestamp, end_timestamp, compacted_content: summary };
183
184 let actions = EventActions { compaction: Some(compaction), ..Default::default() };
185
186 let mut event = Event::new(Event::new("compaction").invocation_id);
187 event.author = "system".to_string();
188 event.actions = actions;
189
190 Ok(Some(event))
191 }
192}