use gadk_genai::{Content, GenerateContentResponseUsageMetadata};
use gadk_model::Backend;
use crate::Event;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SummarizeResult {
pub content: Option<Content>,
pub usage: Option<GenerateContentResponseUsageMetadata>,
}
#[derive(Debug)]
pub struct SummarizeFailure {
pub usage: Option<GenerateContentResponseUsageMetadata>,
pub source: Box<dyn std::error::Error + Send + Sync>,
}
impl std::fmt::Display for SummarizeFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.source, f)
}
}
impl std::error::Error for SummarizeFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&*self.source)
}
}
#[async_trait::async_trait]
pub trait Summarizer: Send + Sync {
async fn summarize_events(
&self,
events: &[Event],
) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>>;
fn type_name(&self) -> &str {
bare_type_name(std::any::type_name::<Self>())
}
fn google_variant(&self) -> Option<Backend> {
None
}
}
#[doc(hidden)]
pub fn bare_type_name(full: &'static str) -> &'static str {
let base = full.split('<').next().unwrap_or(full);
base.rsplit("::").next().unwrap_or(base)
}
#[doc(hidden)]
pub fn failure_usage<'a>(
err: &'a (dyn std::error::Error + Send + Sync + 'static),
) -> Option<&'a GenerateContentResponseUsageMetadata> {
err.downcast_ref::<SummarizeFailure>()
.and_then(|f| f.usage.as_ref())
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use std::sync::Arc;
struct Decliner;
#[async_trait::async_trait]
impl Summarizer for Decliner {
async fn summarize_events(
&self,
_events: &[Event],
) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
Ok(SummarizeResult {
content: None,
usage: Some(GenerateContentResponseUsageMetadata {
prompt_token_count: 7,
..Default::default()
}),
})
}
}
struct Generic<T>(std::marker::PhantomData<T>);
#[async_trait::async_trait]
impl<T: Send + Sync> Summarizer for Generic<T> {
async fn summarize_events(
&self,
events: &[Event],
) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
Ok(SummarizeResult {
content: Some(Content::from_text(
format!("{} events", events.len()),
"model",
)),
usage: None,
})
}
fn google_variant(&self) -> Option<Backend> {
Some(Backend::VertexAi)
}
}
#[test]
fn bare_type_name_strips_path_and_generics() {
assert_eq!(bare_type_name("Foo"), "Foo");
assert_eq!(bare_type_name("a::b::fakeSummarizer"), "fakeSummarizer");
assert_eq!(bare_type_name("a::b::Foo<c::D<e::F>>"), "Foo");
}
#[tokio::test]
async fn summarizer_is_object_safe_and_names_itself() {
let s: Arc<dyn Summarizer> = Arc::new(Decliner);
assert_eq!(s.type_name(), "Decliner");
assert_eq!(s.google_variant(), None);
let res = s.summarize_events(&[]).await.unwrap();
assert!(res.content.is_none(), "a decline has no content");
assert_eq!(res.usage.unwrap().prompt_token_count, 7);
let g: Arc<dyn Summarizer> = Arc::new(Generic::<String>(std::marker::PhantomData));
assert_eq!(g.type_name(), "Generic");
assert_eq!(g.google_variant(), Some(Backend::VertexAi));
let res = g.summarize_events(&[Event::default()]).await.unwrap();
assert_eq!(res.content.unwrap().parts[0].text, "1 events");
}
#[test]
fn failure_usage_reads_a_summarize_failure() {
let usage = GenerateContentResponseUsageMetadata {
prompt_token_count: 4000,
candidates_token_count: 8,
..Default::default()
};
let err: Box<dyn std::error::Error + Send + Sync> = Box::new(SummarizeFailure {
usage: Some(usage.clone()),
source: "summarizer stopped before finishing (finish reason \"MAX_TOKENS\"), so the summary is incomplete".into(),
});
assert_eq!(failure_usage(&*err), Some(&usage));
assert_eq!(
err.to_string(),
"summarizer stopped before finishing (finish reason \"MAX_TOKENS\"), so the summary is incomplete"
);
assert_eq!(err.source().unwrap().to_string(), err.to_string());
let plain: Box<dyn std::error::Error + Send + Sync> = "boom".into();
assert_eq!(failure_usage(&*plain), None);
let no_usage: Box<dyn std::error::Error + Send + Sync> = Box::new(SummarizeFailure {
usage: None,
source: "boom".into(),
});
assert_eq!(failure_usage(&*no_usage), None);
}
}