Skip to main content

adk_agent/
custom_agent.rs

1use crate::invocation_hooks::HookCallbacks;
2use adk_core::{
3    AfterAgentCallback, Agent, BeforeAgentCallback, CallbackContext, Event, EventStream,
4    InvocationContext, Result,
5};
6use async_stream::stream;
7use async_trait::async_trait;
8use futures::StreamExt;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13type RunHandler = Box<
14    dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = Result<EventStream>> + Send>>
15        + Send
16        + Sync,
17>;
18
19/// An agent with a user-defined async handler function.
20///
21/// `CustomAgent` allows you to implement arbitrary agent logic without
22/// conforming to the LLM request/response loop. Use the builder to configure
23/// the handler, sub-agents, and lifecycle callbacks.
24///
25/// The run's invocation hooks (a runner's plugin `before_agent` and `after_agent`
26/// callbacks) run ahead of the agent's own callbacks of the same kind.
27pub struct CustomAgent {
28    name: String,
29    description: String,
30    sub_agents: Vec<Arc<dyn Agent>>,
31    before_callbacks: Arc<Vec<BeforeAgentCallback>>,
32    after_callbacks: Arc<Vec<AfterAgentCallback>>,
33    handler: RunHandler,
34}
35
36impl CustomAgent {
37    /// Create a new builder for `CustomAgent` with the given name.
38    pub fn builder(name: impl Into<String>) -> CustomAgentBuilder {
39        CustomAgentBuilder::new(name)
40    }
41}
42
43#[async_trait]
44impl Agent for CustomAgent {
45    fn name(&self) -> &str {
46        &self.name
47    }
48
49    fn description(&self) -> &str {
50        &self.description
51    }
52
53    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
54        &self.sub_agents
55    }
56
57    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
58        // A call a person asked for needs an agent that holds it for their decision itself
59        // (spec 3.3 §7.4 rule 5).
60        if let Some(refused) = crate::requested_call::refused_by_root(
61            ctx.as_ref(),
62            &self.name,
63            crate::requested_call::RUNS_OTHER_AGENTS,
64        ) {
65            return Ok(refused);
66        }
67        let handler = &self.handler;
68        let before_callbacks = self.before_callbacks.clone();
69        let after_callbacks = self.after_callbacks.clone();
70        let agent_name = self.name.clone();
71        // Runner plugins reach this agent through the run config, ahead of its own callbacks.
72        let HookCallbacks { before_agent: hook_before, after_agent: hook_after, .. } =
73            HookCallbacks::new(&ctx.run_config().invocation_hooks);
74
75        // Execute before callbacks — if any returns content, short-circuit
76        for callback in hook_before.iter().chain(before_callbacks.iter()) {
77            match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
78                Ok(Some(content)) => {
79                    let invocation_id = ctx.invocation_id().to_string();
80                    let s = stream! {
81                        let mut early_event = Event::new(&invocation_id);
82                        early_event.author = agent_name.clone();
83                        early_event.llm_response.content = Some(content);
84                        yield Ok(early_event);
85
86                        for after_cb in hook_after.iter().chain(after_callbacks.iter()) {
87                            match after_cb(ctx.clone() as Arc<dyn CallbackContext>).await {
88                                Ok(Some(after_content)) => {
89                                    let mut after_event = Event::new(&invocation_id);
90                                    after_event.author = agent_name.clone();
91                                    after_event.llm_response.content = Some(after_content);
92                                    yield Ok(after_event);
93                                    return;
94                                }
95                                Ok(None) => continue,
96                                Err(e) => { yield Err(e); return; }
97                            }
98                        }
99                    };
100                    return Ok(Box::pin(s));
101                }
102                Ok(None) => continue,
103                Err(e) => return Err(e),
104            }
105        }
106
107        // Run the actual handler
108        let mut inner_stream = (handler)(ctx.clone()).await?;
109
110        let s = stream! {
111            while let Some(result) = inner_stream.next().await {
112                yield result;
113            }
114
115            // Execute after callbacks
116            for callback in hook_after.iter().chain(after_callbacks.iter()) {
117                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
118                    Ok(Some(content)) => {
119                        let mut after_event = Event::new(ctx.invocation_id());
120                        after_event.author = agent_name.clone();
121                        after_event.llm_response.content = Some(content);
122                        yield Ok(after_event);
123                        break;
124                    }
125                    Ok(None) => continue,
126                    Err(e) => { yield Err(e); return; }
127                }
128            }
129        };
130
131        Ok(Box::pin(s))
132    }
133}
134
135/// Builder for constructing a [`CustomAgent`].
136pub struct CustomAgentBuilder {
137    name: String,
138    description: String,
139    sub_agents: Vec<Arc<dyn Agent>>,
140    before_callbacks: Vec<BeforeAgentCallback>,
141    after_callbacks: Vec<AfterAgentCallback>,
142    handler: Option<RunHandler>,
143}
144
145impl CustomAgentBuilder {
146    /// Create a new builder with the given agent name.
147    pub fn new(name: impl Into<String>) -> Self {
148        Self {
149            name: name.into(),
150            description: String::new(),
151            sub_agents: Vec::new(),
152            before_callbacks: Vec::new(),
153            after_callbacks: Vec::new(),
154            handler: None,
155        }
156    }
157
158    /// Set the agent description.
159    pub fn description(mut self, description: impl Into<String>) -> Self {
160        self.description = description.into();
161        self
162    }
163
164    /// Add a sub-agent.
165    pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
166        self.sub_agents.push(agent);
167        self
168    }
169
170    /// Set all sub-agents, replacing any previously added.
171    pub fn sub_agents(mut self, agents: Vec<Arc<dyn Agent>>) -> Self {
172        self.sub_agents = agents;
173        self
174    }
175
176    /// Add a before-agent callback.
177    pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
178        self.before_callbacks.push(callback);
179        self
180    }
181
182    /// Add an after-agent callback.
183    pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
184        self.after_callbacks.push(callback);
185        self
186    }
187
188    /// Set the async handler function that implements the agent's logic.
189    pub fn handler<F, Fut>(mut self, handler: F) -> Self
190    where
191        F: Fn(Arc<dyn InvocationContext>) -> Fut + Send + Sync + 'static,
192        Fut: Future<Output = Result<EventStream>> + Send + 'static,
193    {
194        self.handler = Some(Box::new(move |ctx| Box::pin(handler(ctx))));
195        self
196    }
197
198    /// Build the [`CustomAgent`], returning an error if no handler was set.
199    pub fn build(self) -> Result<CustomAgent> {
200        let handler = self
201            .handler
202            .ok_or_else(|| adk_core::AdkError::agent("CustomAgent requires a handler"))?;
203
204        // Validate sub-agents have unique names
205        let mut seen_names = std::collections::HashSet::new();
206        for agent in &self.sub_agents {
207            if !seen_names.insert(agent.name()) {
208                return Err(adk_core::AdkError::agent(format!(
209                    "Duplicate sub-agent name: {}",
210                    agent.name()
211                )));
212            }
213        }
214
215        Ok(CustomAgent {
216            name: self.name,
217            description: self.description,
218            sub_agents: self.sub_agents,
219            before_callbacks: Arc::new(self.before_callbacks),
220            after_callbacks: Arc::new(self.after_callbacks),
221            handler,
222        })
223    }
224}