gadk_session/compaction/
summarizer.rs1use gadk_genai::{Content, GenerateContentResponseUsageMetadata};
19use gadk_model::Backend;
20
21use crate::Event;
22
23#[derive(Debug, Clone, Default, PartialEq)]
26pub struct SummarizeResult {
27 pub content: Option<Content>,
29 pub usage: Option<GenerateContentResponseUsageMetadata>,
31}
32
33#[derive(Debug)]
38pub struct SummarizeFailure {
39 pub usage: Option<GenerateContentResponseUsageMetadata>,
41 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#[async_trait::async_trait]
67pub trait Summarizer: Send + Sync {
68 async fn summarize_events(
75 &self,
76 events: &[Event],
77 ) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>>;
78
79 fn type_name(&self) -> &str {
83 bare_type_name(std::any::type_name::<Self>())
84 }
85
86 fn google_variant(&self) -> Option<Backend> {
89 None
90 }
91}
92
93#[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#[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}