Skip to main content

adk_core/
event_summarizer.rs

1//! LLM-based event summarizer for context compaction.
2//!
3//! This module provides [`LlmEventSummarizer`], which uses an LLM to summarize
4//! a window of conversation events into a single compacted event. This is the
5//! Rust equivalent of ADK Python's `LlmEventSummarizer`.
6
7use 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
22/// An LLM-based event summarizer for sliding window compaction.
23///
24/// When called with a list of events, this formats the events, generates a
25/// summary using an LLM, and returns a new [`Event`] containing the summary
26/// within an [`EventCompaction`].
27///
28/// The summarizer's input is the window as the model sees it: the most recent earlier
29/// summary in the window (an event carrying [`EventActions::compaction`]) replaces the events
30/// it covers, so its content carries into the new summary, and every later event contributes
31/// its text, function calls and responses, file and inline data references, and embedded
32/// resources. Thinking, provider-native parts and streamed partial events are left out.
33///
34/// A summary replaces history only when it is complete and smaller. A stream error fails
35/// the summary, and so does a model that stops for any reason but `Stop` (for example
36/// `MaxTokens`), with `model.summary_incomplete`. For a stream error that error keeps the
37/// stream error's category, retry hint, and details, records its code as
38/// `details.metadata["cause_code"]`, and has it as its [`source`](std::error::Error::source).
39/// An empty summary, or one at least as long as the rendered window it would replace, returns
40/// `Ok(None)`, so the runner keeps the history as it is.
41///
42/// The summary call goes through [`crate::generate_metered`], so when the
43/// runner compacts a session it counts against the run's budget and spend
44/// ledger, and a call the budget refuses is never sent.
45pub struct LlmEventSummarizer {
46    llm: Arc<dyn Llm>,
47    prompt_template: String,
48}
49
50impl LlmEventSummarizer {
51    /// Create a new summarizer using the given LLM.
52    pub fn new(llm: Arc<dyn Llm>) -> Self {
53        Self { llm, prompt_template: DEFAULT_PROMPT_TEMPLATE.to_string() }
54    }
55
56    /// Create a new summarizer with a custom prompt template.
57    /// The template must contain `{conversation_history}` as a placeholder.
58    pub fn with_prompt_template(mut self, template: impl Into<String>) -> Self {
59        self.prompt_template = template.into();
60        self
61    }
62
63    /// Renders the window the summary replaces: the latest earlier summary, then each event
64    /// after the span that summary covers.
65    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        // Counts against the run's budget and spend ledger when the runner made a scope current.
110        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        // Drained to the end so the call's usage, which may follow the content, is metered.
117        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        // A summary the model cut short, or declined, would replace history with part of what
144        // it said or with a refusal.
145        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        // A summary at least as long as what it replaces would not shrink the request.
161        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        // A new summary also stands in for the span the earlier one covered.
172        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}