Skip to main content

gadk_agent/
callback.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Callback types: the agent callbacks, the model and tool callbacks, and the plugin callbacks.
17
18use std::sync::Arc;
19
20use futures::future::BoxFuture;
21use gadk_genai::Content;
22use gadk_model::{LlmRequest, LlmResponse, ModelError};
23use gadk_session::Event;
24use serde_json::{Map, Value};
25
26use crate::agent::Agent;
27use crate::context::{Context, InvocationContext};
28use crate::error::{AgentError, ToolError};
29use crate::tool::Tool;
30
31/// Runs before the agent. `Some` content with no error is yielded as an event and skips the
32/// remaining before-agent callbacks, the agent run, and the after-agent callbacks.
33///
34/// An error takes precedence over content, skips the remaining before-agent callbacks, and is
35/// yielded as an `Err` item. If the caller keeps polling, the agent and after-agent callbacks can
36/// still run.
37pub type BeforeAgentCallback =
38    Arc<dyn Fn(Context) -> BoxFuture<'static, Result<Option<Content>, AgentError>> + Send + Sync>;
39
40/// Runs after the agent completes. It is skipped if the invocation has ended or the caller stops
41/// polling before that point. `Some` content or an error skips the remaining after-agent callbacks.
42/// Content is yielded as an event; an error takes precedence and is yielded as an `Err` item.
43pub type AfterAgentCallback =
44    Arc<dyn Fn(Context) -> BoxFuture<'static, Result<Option<Content>, AgentError>> + Send + Sync>;
45
46/// Called before sending a request to the model. If it returns `Some` response or an error, the
47/// actual model call is skipped and the returned response/error is used. The request (possibly
48/// edited) is always handed back.
49pub type BeforeModelCallback = Arc<
50    dyn Fn(
51            Context,
52            LlmRequest,
53        ) -> BoxFuture<'static, (LlmRequest, Result<Option<LlmResponse>, AgentError>)>
54        + Send
55        + Sync,
56>;
57
58/// Called after receiving a response from the model. If it returns `Some` response or an error, the
59/// actual model response/error is replaced with the returned response/error.
60///
61/// The response (possibly edited) is always handed back, mirroring [`BeforeModelCallback`]: an
62/// in-place edit made by a callback that returns `Ok(None)` reaches the later callbacks and the
63/// rest of the flow. Return the received response unchanged when there is nothing to edit.
64pub type AfterModelCallback = Arc<
65    dyn Fn(
66            Context,
67            LlmResponse,
68            Option<Arc<ModelError>>,
69        ) -> BoxFuture<'static, (LlmResponse, Result<Option<LlmResponse>, AgentError>)>
70        + Send
71        + Sync,
72>;
73
74/// Called when the model returns an error. If it returns `Some` response or an error, the actual
75/// model response/error is replaced with the returned response/error.
76pub type OnModelErrorCallback = Arc<
77    dyn Fn(
78            Context,
79            LlmRequest,
80            Arc<ModelError>,
81        ) -> BoxFuture<'static, Result<Option<LlmResponse>, AgentError>>
82        + Send
83        + Sync,
84>;
85
86/// Called before a tool runs. If it returns `Some` result or an error, the remaining callbacks and
87/// the tool call are skipped and the returned result is used as the tool result.
88///
89/// The arguments (possibly edited) are always handed back, mirroring [`BeforeModelCallback`]: the
90/// callbacks and the tool get one copy of the call's arguments, so an edit made by a callback
91/// that returns `Ok(None)` reaches the later callbacks, the tool, and the
92/// on-tool-error and after-tool callbacks. The function call event keeps the model's arguments.
93/// Return the received arguments unchanged when there is nothing to edit.
94pub type BeforeToolCallback = Arc<
95    dyn Fn(
96            Context,
97            Arc<dyn Tool>,
98            Map<String, Value>,
99        ) -> BoxFuture<
100            'static,
101            (
102                Map<String, Value>,
103                Result<Option<Map<String, Value>>, AgentError>,
104            ),
105        > + Send
106        + Sync,
107>;
108
109/// Called after a tool runs, whether it returned a result or an error. If it returns `Some` result
110/// or an error, the remaining callbacks are skipped and the returned result/error is the final
111/// tool output.
112pub type AfterToolCallback = Arc<
113    dyn Fn(
114            Context,
115            Arc<dyn Tool>,
116            Map<String, Value>,
117            Map<String, Value>,
118            Option<Arc<ToolError>>,
119        ) -> BoxFuture<'static, Result<Option<Map<String, Value>>, AgentError>>
120        + Send
121        + Sync,
122>;
123
124/// Called when a tool returns an error. If it returns `Some` result or an error, the tool's
125/// result/error is replaced with the returned one.
126pub type OnToolErrorCallback = Arc<
127    dyn Fn(
128            Context,
129            Arc<dyn Tool>,
130            Map<String, Value>,
131            Arc<ToolError>,
132        ) -> BoxFuture<'static, Result<Option<Map<String, Value>>, AgentError>>
133        + Send
134        + Sync,
135>;
136
137/// Invoked when the user sends a message; may return a replacement message.
138pub type OnUserMessageCallback = Arc<
139    dyn Fn(InvocationContext, Content) -> BoxFuture<'static, Result<Option<Content>, AgentError>>
140        + Send
141        + Sync,
142>;
143
144/// Invoked for each event; may return a replacement event.
145pub type OnEventCallback = Arc<
146    dyn Fn(InvocationContext, Event) -> BoxFuture<'static, Result<Option<Event>, AgentError>>
147        + Send
148        + Sync,
149>;
150
151/// Invoked before a run starts; may return content that short-circuits the run.
152pub type BeforeRunCallback = Arc<
153    dyn Fn(InvocationContext) -> BoxFuture<'static, Result<Option<Content>, AgentError>>
154        + Send
155        + Sync,
156>;
157
158/// Invoked after a run completes.
159pub type AfterRunCallback = Arc<dyn Fn(InvocationContext) -> BoxFuture<'static, ()> + Send + Sync>;
160
161/// Invoked when an error escapes an agent's run.
162///
163/// Notification only: the callbacks of every plugin run in registration order, synchronously,
164/// before the error is yielded, and the error is yielded to the caller unchanged. The agent is the
165/// one that failed (identify it by [`Agent::name`]). The context is a callback context for the
166/// invocation whose actions are discarded: state changes made through it are not persisted, and
167/// artifact saves through it are written but no artifact delta records them.
168///
169/// A panicking callback is caught, so the remaining callbacks still run and the original error is
170/// still yielded; the panic is recorded on the agent's span. The error is compared against the
171/// failing agent's own context: when that context is cancelled, an error that is (or wraps)
172/// [`AgentError::Cancelled`], [`AgentError::DeadlineExceeded`] or the context's cancel cause is
173/// not reported. Errors that escape while the context is live are reported. Parallel sub-agents may
174/// invoke callbacks concurrently. An error from a sub-agent is reported once for each ancestor as
175/// it propagates. A live run (`run_live`) does not invoke this callback.
176pub type OnAgentErrorCallback = Arc<dyn Fn(Context, Arc<dyn Agent>, &AgentError) + Send + Sync>;
177
178/// A plugin's close function.
179pub type CloseFn = Arc<dyn Fn() -> BoxFuture<'static, Result<(), AgentError>> + Send + Sync>;