Skip to main content

gadk_session/compaction/
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//! [`SummarizeResult`] and the [`Summarizer`] trait.
17
18use gadk_genai::{Content, GenerateContentResponseUsageMetadata};
19use gadk_model::Backend;
20
21use crate::Event;
22
23/// What one summarization attempt produced. The two states are
24/// told apart by `content` alone: `Some` is a summary, `None` is a decline.
25#[derive(Debug, Clone, Default, PartialEq)]
26pub struct SummarizeResult {
27    /// The summary, or `None` for a decline.
28    pub content: Option<Content>,
29    /// The token usage the attempt cost, or `None` when unknown. Meaningful on a decline too.
30    pub usage: Option<GenerateContentResponseUsageMetadata>,
31}
32
33/// A summarization failure that still reports what it spent (the usage travels with the
34/// error). Return it boxed from
35/// [`Summarizer::summarize_events`] when a model call was paid for and failed; the framework
36/// records the usage on the compaction span. Display and `source()` are the wrapped error's.
37#[derive(Debug)]
38pub struct SummarizeFailure {
39    /// The token usage the failed attempt cost.
40    pub usage: Option<GenerateContentResponseUsageMetadata>,
41    /// The failure.
42    pub source: Box<dyn std::error::Error + Send + Sync>,
43}
44
45impl std::fmt::Display for SummarizeFailure {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        std::fmt::Display::fmt(&self.source, f)
48    }
49}
50
51impl std::error::Error for SummarizeFailure {
52    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
53        Some(&*self.source)
54    }
55}
56
57/// Condenses a range of events into a single piece of content.
58///
59/// An implementation returns only the summary. The framework builds the event that carries it,
60/// derives the range it covers from the events it handed over, and appends it.
61///
62/// **Cancellation.** The framework cancels a summarization by dropping its future. Post-invocation
63/// compaction can outlast a consumer that stopped reading events, and the framework bounds only
64/// the summarizer it installs by default, so an implementation that calls a model should carry its
65/// own deadline.
66#[async_trait::async_trait]
67pub trait Summarizer: Send + Sync {
68    /// Summarizes `events` into one piece of content, with the token usage the summary cost when
69    /// known. The events passed in are copies; modifying them changes nothing.
70    ///
71    /// `Ok` with `content: None` is a decline: the range was not summarized and history is left
72    /// alone. `Err` is a failure, which is reported and traced; return a boxed
73    /// [`SummarizeFailure`] to report the usage a failure cost.
74    async fn summarize_events(
75        &self,
76        events: &[Event],
77    ) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>>;
78
79    /// The summarizer's bare type name, put on the compaction span as
80    /// `gen_ai.compaction.summarizer_type`. Defaults to the last `::`
81    /// segment of the implementing type's path, without generic arguments.
82    fn type_name(&self) -> &str {
83        bare_type_name(std::any::type_name::<Self>())
84    }
85
86    /// The Google backend the summarizer's model talks to, used for the span's
87    /// `gen_ai.system`. `None` omits the attribute.
88    fn google_variant(&self) -> Option<Backend> {
89        None
90    }
91}
92
93/// The bare name of a `std::any::type_name` path: generic arguments removed, then the last `::`
94/// segment (`a::b::Foo<c::D>` → `Foo`).
95#[doc(hidden)]
96pub fn bare_type_name(full: &'static str) -> &'static str {
97    let base = full.split('<').next().unwrap_or(full);
98    base.rsplit("::").next().unwrap_or(base)
99}
100
101/// The usage a failed summarization reported: `Some` when `err` is a [`SummarizeFailure`] that
102/// carries usage.
103#[doc(hidden)]
104pub fn failure_usage<'a>(
105    err: &'a (dyn std::error::Error + Send + Sync + 'static),
106) -> Option<&'a GenerateContentResponseUsageMetadata> {
107    err.downcast_ref::<SummarizeFailure>()
108        .and_then(|f| f.usage.as_ref())
109}
110
111#[cfg(test)]
112#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
113mod tests {
114    use super::*;
115    use std::sync::Arc;
116
117    struct Decliner;
118
119    #[async_trait::async_trait]
120    impl Summarizer for Decliner {
121        async fn summarize_events(
122            &self,
123            _events: &[Event],
124        ) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
125            Ok(SummarizeResult {
126                content: None,
127                usage: Some(GenerateContentResponseUsageMetadata {
128                    prompt_token_count: 7,
129                    ..Default::default()
130                }),
131            })
132        }
133    }
134
135    struct Generic<T>(std::marker::PhantomData<T>);
136
137    #[async_trait::async_trait]
138    impl<T: Send + Sync> Summarizer for Generic<T> {
139        async fn summarize_events(
140            &self,
141            events: &[Event],
142        ) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
143            Ok(SummarizeResult {
144                content: Some(Content::from_text(
145                    format!("{} events", events.len()),
146                    "model",
147                )),
148                usage: None,
149            })
150        }
151        fn google_variant(&self) -> Option<Backend> {
152            Some(Backend::VertexAi)
153        }
154    }
155
156    #[test]
157    fn bare_type_name_strips_path_and_generics() {
158        assert_eq!(bare_type_name("Foo"), "Foo");
159        assert_eq!(bare_type_name("a::b::fakeSummarizer"), "fakeSummarizer");
160        assert_eq!(bare_type_name("a::b::Foo<c::D<e::F>>"), "Foo");
161    }
162
163    #[tokio::test]
164    async fn summarizer_is_object_safe_and_names_itself() {
165        let s: Arc<dyn Summarizer> = Arc::new(Decliner);
166        assert_eq!(s.type_name(), "Decliner");
167        assert_eq!(s.google_variant(), None);
168        let res = s.summarize_events(&[]).await.unwrap();
169        assert!(res.content.is_none(), "a decline has no content");
170        assert_eq!(res.usage.unwrap().prompt_token_count, 7);
171
172        let g: Arc<dyn Summarizer> = Arc::new(Generic::<String>(std::marker::PhantomData));
173        assert_eq!(g.type_name(), "Generic");
174        assert_eq!(g.google_variant(), Some(Backend::VertexAi));
175        let res = g.summarize_events(&[Event::default()]).await.unwrap();
176        assert_eq!(res.content.unwrap().parts[0].text, "1 events");
177    }
178
179    #[test]
180    fn failure_usage_reads_a_summarize_failure() {
181        let usage = GenerateContentResponseUsageMetadata {
182            prompt_token_count: 4000,
183            candidates_token_count: 8,
184            ..Default::default()
185        };
186        let err: Box<dyn std::error::Error + Send + Sync> = Box::new(SummarizeFailure {
187            usage: Some(usage.clone()),
188            source: "summarizer stopped before finishing (finish reason \"MAX_TOKENS\"), so the summary is incomplete".into(),
189        });
190        assert_eq!(failure_usage(&*err), Some(&usage));
191        assert_eq!(
192            err.to_string(),
193            "summarizer stopped before finishing (finish reason \"MAX_TOKENS\"), so the summary is incomplete"
194        );
195        assert_eq!(err.source().unwrap().to_string(), err.to_string());
196
197        let plain: Box<dyn std::error::Error + Send + Sync> = "boom".into();
198        assert_eq!(failure_usage(&*plain), None);
199        let no_usage: Box<dyn std::error::Error + Send + Sync> = Box::new(SummarizeFailure {
200            usage: None,
201            source: "boom".into(),
202        });
203        assert_eq!(failure_usage(&*no_usage), None);
204    }
205}