use crate::{CallbackContext, Content, LlmRequest, LlmResponse, ReadonlyContext, Result, Tool};
use async_trait::async_trait;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
pub const CALLBACK_PANICKED_CODE: &str = "callback.panicked";
pub async fn guard_callback<T>(
callback: &str,
future: impl Future<Output = Result<T>>,
) -> Result<T> {
use futures::FutureExt;
match std::panic::AssertUnwindSafe(future).catch_unwind().await {
Ok(result) => result,
Err(payload) => {
let detail = payload
.downcast_ref::<&str>()
.map(|text| (*text).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "no message".to_string());
tracing::error!(callback = callback, panic = %detail, "a callback panicked; its step fails closed");
Err(crate::AdkError::new(
crate::ErrorComponent::Agent,
crate::ErrorCategory::Internal,
CALLBACK_PANICKED_CODE,
format!("the {callback} panicked ({detail}); the step it guards did not run"),
))
}
}
}
pub type BeforeAgentCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type AfterAgentCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
#[derive(Debug)]
pub enum BeforeModelResult {
Continue(LlmRequest),
Skip(LlmResponse),
}
pub type BeforeModelCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
LlmRequest,
) -> Pin<Box<dyn Future<Output = Result<BeforeModelResult>> + Send>>
+ Send
+ Sync,
>;
pub type HistoryProcessor = Box<
dyn Fn(
Arc<dyn CallbackContext>,
Vec<Content>,
) -> Pin<Box<dyn Future<Output = Result<Vec<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type AfterModelCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
LlmResponse,
) -> Pin<Box<dyn Future<Output = Result<Option<LlmResponse>>> + Send>>
+ Send
+ Sync,
>;
pub type BeforeToolCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type AfterToolCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
+ Send
+ Sync,
>;
pub type AfterToolCallbackFull = Box<
dyn Fn(
Arc<dyn CallbackContext>,
Arc<dyn Tool>,
serde_json::Value, // args
serde_json::Value, // tool response (success result or error JSON)
) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>>> + Send>>
+ Send
+ Sync,
>;
pub type InstructionProvider = Box<
dyn Fn(Arc<dyn ReadonlyContext>) -> Pin<Box<dyn Future<Output = Result<String>> + Send>>
+ Send
+ Sync,
>;
pub type GlobalInstructionProvider = InstructionProvider;
pub type OnToolErrorCallback = Box<
dyn Fn(
Arc<dyn CallbackContext>,
Arc<dyn Tool>,
serde_json::Value, // args
String, // error message
) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>>> + Send>>
+ Send
+ Sync,
>;
#[async_trait]
pub trait InvocationHooks: std::fmt::Debug + Send + Sync {
async fn before_agent(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
Ok(None)
}
async fn after_agent(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
Ok(None)
}
async fn before_model(
&self,
_ctx: Arc<dyn CallbackContext>,
request: LlmRequest,
) -> Result<BeforeModelResult> {
Ok(BeforeModelResult::Continue(request))
}
async fn after_model(
&self,
_ctx: Arc<dyn CallbackContext>,
_response: LlmResponse,
) -> Result<Option<LlmResponse>> {
Ok(None)
}
async fn on_model_error(
&self,
_ctx: Arc<dyn CallbackContext>,
_request: LlmRequest,
_error: &crate::AdkError,
) -> Result<Option<LlmResponse>> {
Ok(None)
}
fn handles_model_errors(&self) -> bool {
true
}
async fn before_tool(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
Ok(None)
}
async fn after_tool(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
Ok(None)
}
async fn on_tool_error(
&self,
_ctx: Arc<dyn CallbackContext>,
_tool: Arc<dyn Tool>,
_args: serde_json::Value,
_error: String,
) -> Result<Option<serde_json::Value>> {
Ok(None)
}
}
use crate::Event;
#[async_trait]
pub trait BaseEventsSummarizer: Send + Sync {
async fn summarize_events(&self, events: &[Event]) -> Result<Option<Event>>;
}
#[derive(Clone)]
pub struct EventsCompactionConfig {
pub compaction_interval: u32,
pub overlap_size: u32,
pub summarizer: Arc<dyn BaseEventsSummarizer>,
}