adk_core/callbacks.rs
1use crate::{CallbackContext, Content, LlmRequest, LlmResponse, ReadonlyContext, Result, Tool};
2use async_trait::async_trait;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7/// The error code of a callback or plugin that panicked: the step it guards fails closed.
8pub const CALLBACK_PANICKED_CODE: &str = "callback.panicked";
9
10/// Awaits a callback's `future`, turning a panic into a `callback.panicked` error, so a
11/// callback that decides whether a step happens — a before-tool callback, a before-tool
12/// plugin — fails that step closed with a reason instead of unwinding through the agent.
13///
14/// `callback` names the callback in the error, such as `before-tool callback`.
15///
16/// # Example
17///
18/// ```rust
19/// use adk_core::{CALLBACK_PANICKED_CODE, guard_callback};
20///
21/// # futures::executor::block_on(async {
22/// let ok = guard_callback("before-tool callback", async { Ok(1) }).await;
23/// assert_eq!(ok.unwrap(), 1);
24///
25/// let panicked = guard_callback::<()>("before-tool callback", async { panic!("boom") }).await;
26/// let error = panicked.unwrap_err();
27/// assert_eq!(error.code, CALLBACK_PANICKED_CODE);
28/// assert!(error.message.contains("boom"));
29/// # });
30/// ```
31///
32/// # Errors
33///
34/// Returns the callback's own error, or `callback.panicked` when it panicked.
35pub async fn guard_callback<T>(
36 callback: &str,
37 future: impl Future<Output = Result<T>>,
38) -> Result<T> {
39 use futures::FutureExt;
40 match std::panic::AssertUnwindSafe(future).catch_unwind().await {
41 Ok(result) => result,
42 Err(payload) => {
43 let detail = payload
44 .downcast_ref::<&str>()
45 .map(|text| (*text).to_string())
46 .or_else(|| payload.downcast_ref::<String>().cloned())
47 .unwrap_or_else(|| "no message".to_string());
48 tracing::error!(callback = callback, panic = %detail, "a callback panicked; its step fails closed");
49 Err(crate::AdkError::new(
50 crate::ErrorComponent::Agent,
51 crate::ErrorCategory::Internal,
52 CALLBACK_PANICKED_CODE,
53 format!("the {callback} panicked ({detail}); the step it guards did not run"),
54 ))
55 }
56 }
57}
58
59// Agent callbacks
60/// Callback invoked before an agent runs. Return `Ok(Some(content))` to short-circuit.
61pub type BeforeAgentCallback = Box<
62 dyn Fn(
63 Arc<dyn CallbackContext>,
64 ) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
65 + Send
66 + Sync,
67>;
68/// Callback invoked after an agent completes. Return `Ok(Some(content))` to override.
69pub type AfterAgentCallback = Box<
70 dyn Fn(
71 Arc<dyn CallbackContext>,
72 ) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
73 + Send
74 + Sync,
75>;
76
77/// Result from a BeforeModel callback
78#[derive(Debug)]
79pub enum BeforeModelResult {
80 /// Continue with the (possibly modified) request
81 Continue(LlmRequest),
82 /// Skip the model call and use this response instead
83 Skip(LlmResponse),
84}
85
86// Model callbacks
87// BeforeModelCallback can modify the request or skip the model call entirely
88/// Callback invoked before a model call. Can modify the request or skip the call entirely.
89pub type BeforeModelCallback = Box<
90 dyn Fn(
91 Arc<dyn CallbackContext>,
92 LlmRequest,
93 ) -> Pin<Box<dyn Future<Output = Result<BeforeModelResult>> + Send>>
94 + Send
95 + Sync,
96>;
97/// Rewrites an agent's conversation history before each model request of a turn.
98///
99/// Receives the history the agent continues from and returns its replacement: later steps of
100/// the turn append to the returned contents, so a compaction runs once and carries over. The
101/// history holds the agent's own contents only, never what a toolset, plugin, invocation hook
102/// or [`BeforeModelCallback`] adds to one request. An error ends the turn with that error.
103///
104/// A cut that keeps a function response without its call is rejected by providers;
105/// [`balanced_content_cut`](crate::history::balanced_content_cut) finds a safe one.
106pub type HistoryProcessor = Box<
107 dyn Fn(
108 Arc<dyn CallbackContext>,
109 Vec<Content>,
110 ) -> Pin<Box<dyn Future<Output = Result<Vec<Content>>> + Send>>
111 + Send
112 + Sync,
113>;
114/// Callback invoked after a model call. Return `Ok(Some(response))` to override.
115pub type AfterModelCallback = Box<
116 dyn Fn(
117 Arc<dyn CallbackContext>,
118 LlmResponse,
119 ) -> Pin<Box<dyn Future<Output = Result<Option<LlmResponse>>> + Send>>
120 + Send
121 + Sync,
122>;
123
124// Tool callbacks
125/// Callback invoked before a tool executes. Return `Ok(Some(content))` to skip execution.
126///
127/// `LlmAgent` answers the skipped call with the content: a function response part is sent with
128/// the call's id and tool name, and text-only content as the call's `{"error": <text>}` result.
129pub type BeforeToolCallback = Box<
130 dyn Fn(
131 Arc<dyn CallbackContext>,
132 ) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
133 + Send
134 + Sync,
135>;
136/// Callback invoked after a tool executes. Return `Ok(Some(content))` to override the result.
137///
138/// `LlmAgent` sends a function response part with the call's id and tool name, and text-only
139/// content as the call's `{"result": <text>}` result.
140pub type AfterToolCallback = Box<
141 dyn Fn(
142 Arc<dyn CallbackContext>,
143 ) -> Pin<Box<dyn Future<Output = Result<Option<Content>>> + Send>>
144 + Send
145 + Sync,
146>;
147
148/// Rich after-tool callback that receives the tool, arguments, and response.
149///
150/// Aligned with the Python/Go ADK model where `after_tool_callback` receives
151/// the full tool execution context: the tool itself, the arguments it was
152/// called with, and the response it produced (or error JSON).
153///
154/// This is the V2 callback surface for first-class tool result handling.
155/// Unlike [`AfterToolCallback`] (which only receives `CallbackContext`),
156/// this callback can inspect and modify tool results without relying on
157/// `ToolOutcome` inspection.
158///
159/// Return `Ok(None)` to keep the original response, or `Ok(Some(value))`
160/// to replace the function response sent to the LLM.
161pub type AfterToolCallbackFull = Box<
162 dyn Fn(
163 Arc<dyn CallbackContext>,
164 Arc<dyn Tool>,
165 serde_json::Value, // args
166 serde_json::Value, // tool response (success result or error JSON)
167 ) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>>> + Send>>
168 + Send
169 + Sync,
170>;
171
172// Instruction providers - dynamic instruction generation
173/// Async function that generates dynamic instructions from context.
174pub type InstructionProvider = Box<
175 dyn Fn(Arc<dyn ReadonlyContext>) -> Pin<Box<dyn Future<Output = Result<String>> + Send>>
176 + Send
177 + Sync,
178>;
179/// Alias for [`InstructionProvider`] used at the global (runner) level.
180pub type GlobalInstructionProvider = InstructionProvider;
181
182// ===== Error Callbacks =====
183
184/// Callback invoked when a tool execution fails (after retries are exhausted).
185///
186/// This is the canonical, framework-level tool-error callback type shared by
187/// `adk-agent` (builder registration) and `adk-plugin` (plugin hooks).
188///
189/// Returns `Ok(Some(value))` to substitute a fallback result as the function
190/// response to the LLM, or `Ok(None)` to let the next callback (or the
191/// original error) propagate.
192pub type OnToolErrorCallback = Box<
193 dyn Fn(
194 Arc<dyn CallbackContext>,
195 Arc<dyn Tool>,
196 serde_json::Value, // args
197 String, // error message
198 ) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>>> + Send>>
199 + Send
200 + Sync,
201>;
202
203// ===== Invocation Hooks =====
204
205/// Hooks applied to every model and tool call in a runner invocation.
206///
207/// An agent's own callbacks cover only that agent. Hooks installed on
208/// [`RunConfig::invocation_hooks`](crate::RunConfig::invocation_hooks) reach every agent the
209/// invocation runs — transfer targets and agents behind an agent tool included — because the
210/// `RunConfig` travels with the invocation. The runner installs its plugin manager here.
211///
212/// An agent runs these hooks ahead of its own callbacks of the same kind, with the same
213/// semantics: a hook that returns a value short-circuits the agent's callbacks of that kind, and
214/// a hook that returns an error is handled exactly as a failing agent callback.
215///
216/// Every method defaults to a pass-through, so an implementation overrides only the hooks it
217/// needs.
218///
219/// # Example
220///
221/// ```rust
222/// use adk_core::{CallbackContext, Content, InvocationHooks, Result, RunConfig, async_trait};
223/// use std::sync::Arc;
224///
225/// /// Refuses every call to `delete_file`, whichever agent makes it.
226/// #[derive(Debug)]
227/// struct NoDeletes;
228///
229/// #[async_trait]
230/// impl InvocationHooks for NoDeletes {
231/// async fn before_tool(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
232/// if ctx.tool_name() == Some("delete_file") {
233/// return Ok(Some(Content::new("function").with_text("delete_file is disabled")));
234/// }
235/// Ok(None)
236/// }
237/// }
238///
239/// let config = RunConfig::builder().invocation_hook(Arc::new(NoDeletes)).build();
240/// assert_eq!(config.invocation_hooks.len(), 1);
241/// ```
242#[async_trait]
243pub trait InvocationHooks: std::fmt::Debug + Send + Sync {
244 /// Runs before an agent starts. `Some(content)` skips the agent and emits `content`.
245 async fn before_agent(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
246 Ok(None)
247 }
248
249 /// Runs after an agent finishes. `Some(content)` is emitted as a final event.
250 async fn after_agent(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
251 Ok(None)
252 }
253
254 /// Runs before each model call. May rewrite the request or skip the call.
255 async fn before_model(
256 &self,
257 _ctx: Arc<dyn CallbackContext>,
258 request: LlmRequest,
259 ) -> Result<BeforeModelResult> {
260 Ok(BeforeModelResult::Continue(request))
261 }
262
263 /// Runs on each model response chunk. `Some(response)` replaces the chunk.
264 async fn after_model(
265 &self,
266 _ctx: Arc<dyn CallbackContext>,
267 _response: LlmResponse,
268 ) -> Result<Option<LlmResponse>> {
269 Ok(None)
270 }
271
272 /// Runs when a model call fails, or its response stream fails, before the agent reports
273 /// the error. `request` is the request the model was sent.
274 ///
275 /// `Some(response)` answers the turn instead, as a model-fallback plugin does: the agent
276 /// processes it as the model's response, so its tool calls run and its text is the
277 /// answer. A refusal by the run's own budget or spend ledger is not a model failure and
278 /// does not reach this hook.
279 async fn on_model_error(
280 &self,
281 _ctx: Arc<dyn CallbackContext>,
282 _request: LlmRequest,
283 _error: &crate::AdkError,
284 ) -> Result<Option<LlmResponse>> {
285 Ok(None)
286 }
287
288 /// Whether [`on_model_error`](Self::on_model_error) can answer a failed model call.
289 ///
290 /// An agent keeps a copy of every request it sends, for this hook, while any of the run's
291 /// hooks returns `true`. The default is `true`; an implementation whose `on_model_error`
292 /// always returns `Ok(None)` returns `false`, so the agent sends the request without
293 /// copying the conversation first.
294 ///
295 /// # Example
296 ///
297 /// ```rust
298 /// use adk_core::InvocationHooks;
299 ///
300 /// /// Observes tool calls only.
301 /// #[derive(Debug)]
302 /// struct ToolAudit;
303 ///
304 /// impl InvocationHooks for ToolAudit {
305 /// fn handles_model_errors(&self) -> bool {
306 /// false
307 /// }
308 /// }
309 ///
310 /// assert!(!ToolAudit.handles_model_errors());
311 /// ```
312 fn handles_model_errors(&self) -> bool {
313 true
314 }
315
316 /// Runs before each tool call. `ctx.tool_name()` and `ctx.tool_input()` describe the call.
317 ///
318 /// `Some(content)` skips the tool and reports `content` as its result.
319 async fn before_tool(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
320 Ok(None)
321 }
322
323 /// Runs after each tool call. `Some(content)` replaces the tool's response.
324 async fn after_tool(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
325 Ok(None)
326 }
327
328 /// Runs when a tool fails after its retries. `Some(value)` replaces the error result.
329 async fn on_tool_error(
330 &self,
331 _ctx: Arc<dyn CallbackContext>,
332 _tool: Arc<dyn Tool>,
333 _args: serde_json::Value,
334 _error: String,
335 ) -> Result<Option<serde_json::Value>> {
336 Ok(None)
337 }
338}
339
340// ===== Context Compaction =====
341
342use crate::Event;
343
344/// Trait for summarizing events during context compaction.
345///
346/// Implementations receive a window of events and produce a single
347/// compacted event containing a summary. The runner calls this when
348/// the compaction interval is reached.
349#[async_trait]
350pub trait BaseEventsSummarizer: Send + Sync {
351 /// Summarize the given events into a single compacted event.
352 /// Returns `None` if no compaction is needed (e.g., empty input).
353 async fn summarize_events(&self, events: &[Event]) -> Result<Option<Event>>;
354}
355
356/// Configuration for automatic context compaction.
357///
358/// Mirrors ADK Python's `EventsCompactionConfig`:
359/// - `compaction_interval`: Number of invocations before triggering compaction
360/// - `overlap_size`: Events from the previous window to include in the next summary
361/// - `summarizer`: The strategy used to produce summaries
362#[derive(Clone)]
363pub struct EventsCompactionConfig {
364 /// Number of completed invocations that triggers compaction.
365 pub compaction_interval: u32,
366 /// How many events from the previous compacted window to include
367 /// in the next compaction for continuity.
368 pub overlap_size: u32,
369 /// The summarizer implementation (e.g., LLM-based).
370 pub summarizer: Arc<dyn BaseEventsSummarizer>,
371}