Skip to main content

gadk_session/compaction/
llm_summarizer.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The default, model-backed [`Summarizer`].
17
18use std::sync::Arc;
19use std::time::Duration;
20
21use async_trait::async_trait;
22use futures::StreamExt;
23use gadk_genai::{Content, FinishReason, GenerateContentConfig, Part};
24use gadk_model::{Backend, Llm, LlmRequest, ModelError};
25
26use super::go_fmt::{as_go_floats, go_sprint};
27use super::{
28    CompactionConfigError, SummarizeFailure, SummarizeResult, Summarizer, content, is_prose_part,
29};
30use crate::Event;
31
32type BoxError = Box<dyn std::error::Error + Send + Sync>;
33
34/// The token an [`LlmSummarizer`] prompt template must contain. It is replaced with the rendered
35/// event transcript.
36pub const CONVERSATION_HISTORY_PLACEHOLDER: &str = "{conversation_history}";
37
38/// The default prompt, as a single template with the placeholder.
39pub(crate) const DEFAULT_PROMPT_TEMPLATE: &str = concat!(
40    "The following is a conversation history between a user and an AI agent.",
41    " It may or may not start from a compacted history. Please identify and",
42    " reiterate the user request, summarize the context so far, focusing on",
43    " key decisions made and information obtained, as well as any unresolved",
44    " questions or tasks. ",
45    "CRITICAL INSTRUCTIONS: ",
46    "1. Explicitly identify and state the primary language used by the user ",
47    "at the top of your summary (e.g., \"Conversation Language: English\"). ",
48    "2. If the agent called any tools, accurately list the exact tool names ",
49    "used to maintain tool grounding. ",
50    "3. Maintain a section titled \"Durable facts\" listing every concrete ",
51    "detail the user has stated: identifiers, names, dates, numbers, chosen ",
52    "options and the reasons given for them. Copy each one verbatim. This ",
53    "history may already be a summary of a summary, so any durable fact ",
54    "present in the history MUST be carried forward unchanged, even if it is ",
55    "old and the recent turns are about something else. Never drop or ",
56    "generalize a durable fact to save space; drop narrative instead. ",
57    "The rest of the summary should be concise and capture the",
58    " essence of the interaction.\n\n",
59    "{conversation_history}"
60);
61
62/// Default per-part character cap in the transcript.
63const DEFAULT_MAX_TOOL_CONTENT_CHARS: i32 = 2000;
64/// Default whole-transcript character budget.
65const DEFAULT_MAX_TRANSCRIPT_CHARS: i32 = 200_000;
66/// Room reserved per part for "... [truncated N chars]".
67const TRUNCATION_SUFFIX_BUDGET: i32 = 32;
68/// Every character that can end a transcript line.
69pub(crate) const LINE_BREAKERS: &str = "\r\n\u{b}\u{c}\u{85}\u{2028}\u{2029}";
70
71/// Settings for an [`LlmSummarizer`].
72#[derive(Clone, Default)]
73pub struct LlmSummarizerConfig {
74    /// The model that writes the summary. Required.
75    pub model: Option<Arc<dyn Llm>>,
76    /// The prompt; must contain [`CONVERSATION_HISTORY_PLACEHOLDER`]. Empty uses the default,
77    /// which requires concrete values to be carried forward verbatim.
78    pub prompt_template: String,
79    /// Per-part character cap in the transcript. 0 uses 2000; negative disables truncation.
80    pub max_tool_content_chars: i32,
81    /// Whole-transcript character budget. 0 uses 200 000; negative disables the budget.
82    pub max_transcript_chars: i32,
83    /// Bound on the model call. Zero means no timeout.
84    pub timeout: Duration,
85    /// Generation config; only safety settings, temperature, top-p, top-k, seed and labels
86    /// carry over.
87    pub generate_content_config: Option<GenerateContentConfig>,
88}
89
90/// Summarizes events by asking a model.
91pub struct LlmSummarizer {
92    pub(crate) model: Arc<dyn Llm>,
93    pub(crate) prompt_template: String,
94    pub(crate) max_tool_content_chars: i32,
95    pub(crate) max_transcript_chars: i32,
96    pub(crate) gen_config: Option<GenerateContentConfig>,
97    pub(crate) timeout: Duration,
98}
99
100/// The error of a failed model call: `summarizer model call failed: <cause>`.
101#[derive(Debug, thiserror::Error)]
102enum ModelCallFailed {
103    #[error("summarizer model call failed: {0}")]
104    Model(#[source] ModelError),
105    #[error("summarizer model call failed: context deadline exceeded")]
106    DeadlineExceeded,
107}
108
109impl LlmSummarizer {
110    /// Creates a summarizer; fails when the config has no model or a prompt template without
111    /// [`CONVERSATION_HISTORY_PLACEHOLDER`].
112    pub fn new(cfg: LlmSummarizerConfig) -> Result<LlmSummarizer, CompactionConfigError> {
113        let Some(model) = cfg.model else {
114            return Err(CompactionConfigError::new(
115                "LlmSummarizerConfig.model is required",
116            ));
117        };
118        let template = if cfg.prompt_template.is_empty() {
119            DEFAULT_PROMPT_TEMPLATE.to_owned()
120        } else {
121            cfg.prompt_template
122        };
123        if !template.contains(CONVERSATION_HISTORY_PLACEHOLDER) {
124            return Err(CompactionConfigError::new(format!(
125                "prompt_template must contain the placeholder \"{CONVERSATION_HISTORY_PLACEHOLDER}\""
126            )));
127        }
128        let max_transcript = if cfg.max_transcript_chars == 0 {
129            DEFAULT_MAX_TRANSCRIPT_CHARS
130        } else {
131            cfg.max_transcript_chars
132        };
133        let max_chars = if cfg.max_tool_content_chars == 0 {
134            DEFAULT_MAX_TOOL_CONTENT_CHARS
135        } else {
136            cfg.max_tool_content_chars
137        };
138        Ok(LlmSummarizer {
139            model,
140            prompt_template: template,
141            max_tool_content_chars: max_chars,
142            max_transcript_chars: max_transcript,
143            timeout: cfg.timeout,
144            gen_config: summarizer_gen_config(cfg.generate_content_config.as_ref()),
145        })
146    }
147
148    /// Calls the model with `req` and returns the first complete response that has text; a finish
149    /// reason other than `Stop`, or no usable content, is an error.
150    async fn call_model(&self, req: LlmRequest) -> Result<SummarizeResult, BoxError> {
151        let mut responses = self.model.generate_content(req, false);
152        let mut finish_reason: Option<FinishReason> = None;
153        while let Some(item) = responses.next().await {
154            let resp = item.map_err(ModelCallFailed::Model)?;
155            // A streamed fragment is not the summary.
156            if resp.partial {
157                continue;
158            }
159            if let Some(r) = &resp.finish_reason {
160                finish_reason = Some(r.clone());
161            }
162            if !has_text(resp.content.as_ref()) {
163                continue;
164            }
165            if let Some(r) = finish_reason.as_ref().filter(|r| **r != FinishReason::Stop) {
166                return Err(Box::new(SummarizeFailure {
167                    usage: resp.usage_metadata,
168                    source: format!(
169                        "summarizer stopped before finishing (finish reason \"{}\"), so the summary is incomplete",
170                        r.as_str()
171                    )
172                    .into(),
173                }));
174            }
175            return Ok(SummarizeResult {
176                content: resp.content,
177                usage: resp.usage_metadata,
178            });
179        }
180        match finish_reason {
181            Some(r) => Err(format!(
182                "summarizer returned no usable content (finish reason \"{}\")",
183                r.as_str()
184            )
185            .into()),
186            None => Err("summarizer returned no usable content".into()),
187        }
188    }
189
190    /// One transcript line per rendered part.
191    pub(crate) fn format_events(&self, events: &[Event], cap: i32) -> String {
192        let mut lines: Vec<String> = Vec::new();
193        for ev in events {
194            let Some(c) = content(ev).filter(|c| !c.parts.is_empty()) else {
195                continue;
196            };
197            let is_compaction = ev.actions.compaction.is_some();
198            let author = escape_lines(&ev.author);
199            for p in &c.parts {
200                if p.thought && !p.text.is_empty() {
201                    // A previous summary's own reasoning is not folded into the next one.
202                    if !is_compaction {
203                        lines.push(format!(
204                            "{author} (thought): {}",
205                            escape_lines(&self.truncate_to(&p.text, cap))
206                        ));
207                    }
208                } else if !p.text.is_empty() {
209                    lines.push(format!(
210                        "{author}: {}",
211                        escape_lines(&self.truncate_to(&p.text, cap))
212                    ));
213                }
214                if let Some(fc) = &p.function_call {
215                    lines.push(format!(
216                        "{author} called tool: {}({})",
217                        escape_lines(&fc.name),
218                        escape_lines(&self.truncate_to(&stringify(&fc.args), cap))
219                    ));
220                }
221                if let Some(fr) = &p.function_response {
222                    lines.push(format!(
223                        "Tool response from {}: {}",
224                        escape_lines(&fr.name),
225                        escape_lines(&self.truncate_to(&stringify(&fr.response), cap))
226                    ));
227                }
228                let kind = placeholder_kind(p);
229                if !kind.is_empty() {
230                    lines.push(format!(
231                        "{author}: [{}]",
232                        escape_lines(&self.truncate_to(&kind, cap))
233                    ));
234                }
235            }
236        }
237        lines.join("\n")
238    }
239
240    /// Caps `text` at `cap` characters (negative = no cap), ending with `... [truncated N chars]`
241    /// when cut.
242    pub(crate) fn truncate_to(&self, text: &str, cap: i32) -> String {
243        let Ok(cap) = usize::try_from(cap) else {
244            return text.to_owned();
245        };
246        if text.len() <= cap {
247            return text.to_owned();
248        }
249        let n = text.chars().count();
250        if n <= cap {
251            return text.to_owned();
252        }
253        let kept: String = text.chars().take(cap).collect();
254        format!("{kept}... [truncated {} chars]", n - cap)
255    }
256
257    /// The transcript within the budget, after one shrink pass; refused when it still does not fit.
258    pub(crate) fn render_transcript(&self, events: &[Event]) -> Result<String, BoxError> {
259        let mut transcript = self.format_events(events, self.max_tool_content_chars);
260        let mut size = rune_count(&transcript);
261        if self.max_transcript_chars < 0 || size <= self.max_transcript_chars {
262            return Ok(transcript);
263        }
264        let parts = count_rendered_parts(events);
265        if parts > 0 {
266            let cap = self.max_transcript_chars / parts - self.per_part_overhead(events);
267            if cap > 0 && (self.max_tool_content_chars < 0 || cap < self.max_tool_content_chars) {
268                let shrunk = self.format_events(events, cap);
269                let shrunk_size = rune_count(&shrunk);
270                if shrunk_size < size {
271                    transcript = shrunk;
272                    size = shrunk_size;
273                }
274            }
275        }
276        if size <= self.max_transcript_chars {
277            return Ok(transcript);
278        }
279        Err(format!(
280            "rendered transcript is {size} characters, over the {} limit, for a window of {} events: compact a smaller window",
281            self.max_transcript_chars,
282            events.len()
283        )
284        .into())
285    }
286
287    /// The longest author (in bytes) plus ": " and the newline, plus the truncation-suffix budget.
288    fn per_part_overhead(&self, events: &[Event]) -> i32 {
289        let longest = events.iter().map(|ev| ev.author.len()).max().unwrap_or(0);
290        i32::try_from(longest)
291            .unwrap_or(i32::MAX)
292            .saturating_add(3 + TRUNCATION_SUFFIX_BUDGET)
293    }
294}
295
296#[async_trait]
297impl Summarizer for LlmSummarizer {
298    /// Summarizes `events` by calling the model on their transcript.
299    async fn summarize_events(&self, events: &[Event]) -> Result<SummarizeResult, BoxError> {
300        if events.is_empty() {
301            return Ok(SummarizeResult::default());
302        }
303        let transcript = self.render_transcript(events)?;
304        let prompt =
305            self.prompt_template
306                .replacen(CONVERSATION_HISTORY_PLACEHOLDER, &transcript, 1);
307        let req = LlmRequest {
308            model: self.model.name().to_owned(),
309            contents: vec![Content::from_text(prompt, "user")],
310            // Every call owns its config.
311            config: self.gen_config.clone(),
312            ..Default::default()
313        };
314        if self.timeout.is_zero() {
315            return self.call_model(req).await;
316        }
317        match tokio::time::timeout(self.timeout, self.call_model(req)).await {
318            Ok(res) => res,
319            Err(_) => Err(Box::new(ModelCallFailed::DeadlineExceeded)),
320        }
321    }
322
323    /// The type name reported on the compaction span.
324    fn type_name(&self) -> &str {
325        "LLMSummarizer"
326    }
327
328    /// The Google backend of the model, if any.
329    fn google_variant(&self) -> Option<Backend> {
330        self.model.google_variant()
331    }
332}
333
334/// True for a non-thought part with non-blank text.
335fn has_text(c: Option<&Content>) -> bool {
336    c.is_some_and(|c| {
337        c.parts
338            .iter()
339            .any(|p| !p.thought && !p.text.trim().is_empty())
340    })
341}
342
343/// The number of characters in `s`, as the i32 the budgets use.
344fn rune_count(s: &str) -> i32 {
345    i32::try_from(s.chars().count()).unwrap_or(i32::MAX)
346}
347
348/// `{k1: v1, k2: v2}` with sorted keys and `%v`-style values; `""` when empty.
349fn stringify(v: &serde_json::Map<String, serde_json::Value>) -> String {
350    if v.is_empty() {
351        return String::new();
352    }
353    let mut keys: Vec<&String> = v.keys().collect();
354    keys.sort();
355    let body = keys
356        .iter()
357        .map(|k| format!("{k}: {}", go_sprint(&as_go_floats(&v[k.as_str()]))))
358        .collect::<Vec<_>>()
359        .join(", ");
360    format!("{{{body}}}")
361}
362
363/// Replaces every line break with `\n`; a `\r\n` pair becomes one `\n`.
364fn escape_lines(text: &str) -> String {
365    if !text.contains(|c| LINE_BREAKERS.contains(c)) {
366        return text.to_owned();
367    }
368    let mut out = String::with_capacity(text.len() + 8);
369    let mut chars = text.chars().peekable();
370    while let Some(c) = chars.next() {
371        if c == '\r' && chars.peek() == Some(&'\n') {
372            chars.next();
373            out.push_str("\\n");
374        } else if LINE_BREAKERS.contains(c) {
375            out.push_str("\\n");
376        } else {
377            out.push(c);
378        }
379    }
380    out
381}
382
383/// Keeps only what shapes prose: safety settings, temperature, top-p, top-k, seed and labels.
384pub(crate) fn summarizer_gen_config(
385    cfg: Option<&GenerateContentConfig>,
386) -> Option<GenerateContentConfig> {
387    let cfg = cfg?;
388    Some(GenerateContentConfig {
389        safety_settings: cfg.safety_settings.clone(),
390        temperature: cfg.temperature,
391        top_p: cfg.top_p,
392        top_k: cfg.top_k,
393        seed: cfg.seed,
394        labels: cfg.labels.clone(),
395        ..Default::default()
396    })
397}
398
399/// The stand-in for a part the transcript cannot render.
400fn placeholder_kind(p: &Part) -> String {
401    if let Some(b) = &p.inline_data {
402        mime_or(&b.mime_type, "inline data")
403    } else if let Some(f) = &p.file_data {
404        mime_or(&f.mime_type, "file")
405    } else if p.executable_code.is_some() {
406        "executable code".to_owned()
407    } else if p.code_execution_result.is_some() {
408        "code execution result".to_owned()
409    } else {
410        String::new()
411    }
412}
413
414/// `fallback` when `mime_type` is empty, else `"<mime_type> attachment"`.
415fn mime_or(mime_type: &str, fallback: &str) -> String {
416    if mime_type.is_empty() {
417        fallback.to_owned()
418    } else {
419        format!("{mime_type} attachment")
420    }
421}
422
423/// How many transcript lines a window renders.
424pub(crate) fn count_rendered_parts(events: &[Event]) -> i32 {
425    let mut n = 0i32;
426    for ev in events {
427        let Some(c) = content(ev) else { continue };
428        for p in &c.parts {
429            if !p.text.is_empty()
430                || p.function_call.is_some()
431                || p.function_response.is_some()
432                || is_prose_part(p)
433                || !placeholder_kind(p).is_empty()
434            {
435                n += 1;
436            }
437        }
438    }
439    n
440}
441
442#[cfg(test)]
443#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
444mod tests {
445    use super::*;
446
447    #[test]
448    fn escape_lines_treats_crlf_as_one_break() {
449        assert_eq!(escape_lines("a\r\nb\rc\nd\u{2028}e"), "a\\nb\\nc\\nd\\ne");
450        assert_eq!(escape_lines("plain"), "plain");
451    }
452
453    #[test]
454    fn default_template_ends_with_the_placeholder() {
455        assert!(
456            DEFAULT_PROMPT_TEMPLATE.ends_with(&format!("\n\n{CONVERSATION_HISTORY_PLACEHOLDER}"))
457        );
458        assert_eq!(
459            DEFAULT_PROMPT_TEMPLATE
460                .matches(CONVERSATION_HISTORY_PLACEHOLDER)
461                .count(),
462            1
463        );
464    }
465
466    #[test]
467    fn summarizer_gen_config_keeps_the_six_fields() {
468        let input = GenerateContentConfig {
469            temperature: Some(0.1),
470            top_p: Some(0.2),
471            top_k: Some(3.0),
472            seed: Some(4),
473            labels: [("k".to_owned(), "v".to_owned())].into(),
474            max_output_tokens: 9,
475            ..Default::default()
476        };
477        let got = summarizer_gen_config(Some(&input)).unwrap();
478        assert_eq!(
479            (
480                got.temperature,
481                got.top_p,
482                got.top_k,
483                got.seed,
484                got.labels.clone(),
485                got.max_output_tokens
486            ),
487            (
488                Some(0.1),
489                Some(0.2),
490                Some(3.0),
491                Some(4),
492                input.labels.clone(),
493                0
494            )
495        );
496        assert!(summarizer_gen_config(None).is_none());
497    }
498}