pub use adk_core::OnToolErrorCallback;
use adk_core::{
CallbackContext, Content, Event, InvocationContext, LlmRequest, LlmResponse, Result,
};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
pub type OnUserMessageCallback = Box<
dyn Fn(
Arc<dyn InvocationContext>,
Content,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type OnEventCallback = Box<
dyn Fn(
Arc<dyn InvocationContext>,
Event,
) -> Pin<Box<dyn Future<Output = Result<Option<Event>>> + Send>>
+ Send
+ Sync,
>;
pub type BeforeRunCallback = Box<
dyn Fn(
Arc<dyn InvocationContext>,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type AfterRunCallback = Box<
dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
>;
pub type OnModelErrorCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
LlmRequest,
String, // error message
) -> Pin<Box<dyn Future<Output = Result<Option<LlmResponse>>> + Send>>
+ Send
+ Sync,
>;
pub fn log_user_messages() -> OnUserMessageCallback {
Box::new(|_ctx, content| {
Box::pin(async move {
tracing::info!(role = %content.role, parts = ?content.parts.len(), "User message received");
Ok(None)
})
})
}
pub fn log_events() -> OnEventCallback {
Box::new(|_ctx, event| {
Box::pin(async move {
tracing::info!(
id = %event.id,
author = %event.author,
partial = event.llm_response.partial,
"Event generated"
);
Ok(None)
})
})
}
pub fn collect_metrics(
on_run_start: impl Fn() + Send + Sync + 'static,
on_run_end: impl Fn() + Send + Sync + 'static,
) -> (BeforeRunCallback, AfterRunCallback) {
let start_fn = Arc::new(on_run_start);
let end_fn = Arc::new(on_run_end);
let before = Box::new(move |_ctx: Arc<dyn InvocationContext>| {
let f = start_fn.clone();
Box::pin(async move {
f();
Ok(None)
}) as Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
});
let after = Box::new(move |_ctx: Arc<dyn InvocationContext>| {
let f = end_fn.clone();
Box::pin(async move {
f();
}) as Pin<Box<dyn Future<Output = ()> + Send>>
});
(before, after)
}