Skip to main content

gadk_engine/tool/
agent_tool.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//! `AgentTool`, `AgentToolConfig`: run an agent as a tool.
17
18use std::any::Any;
19use std::collections::BTreeSet;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use futures::StreamExt;
24use gadk_agent::{
25    Agent, AgentError, Context, RunConfig, RunnableTool, StreamingMode, Tool, ToolError,
26    ToolOriginKind,
27};
28use gadk_genai::{Content, FunctionDeclaration, ROLE_USER};
29use gadk_session::{CreateRequest, InMemorySessionService, SessionService};
30use serde_json::{Map, Value};
31
32use crate::artifacts::new_forwarding_service;
33use crate::llm::processors::{as_go_floats, go_json_marshal, go_sprint};
34use crate::llm::state::reveal;
35use crate::runner::{PluginConfig, RunOptions, Runner, RunnerConfig};
36use crate::tool::single_turn::{input_schema_of, make_function_declaration};
37use crate::tool::utils::{go_type_name, validate_map_on_schema, validate_output_schema};
38use crate::workflow::route::go_quote;
39
40/// Configuration of an [`AgentTool`].
41#[derive(Clone, Default)]
42pub struct AgentToolConfig {
43    /// If true, the calling agent skips summarization after the sub-agent finishes.
44    pub skip_summarization: bool,
45}
46
47/// A tool that runs an agent in a child runner over a fresh
48/// in-memory session and returns its final answer.
49pub struct AgentTool {
50    agent: Arc<dyn Agent>,
51    skip_summarization: bool,
52}
53
54impl AgentTool {
55    /// Wraps `agent` as a tool; `None` means `skip_summarization = false`.
56    #[allow(clippy::new_ret_no_self)] // returns the tool as `Arc<dyn Tool>`
57    pub fn new(agent: Arc<dyn Agent>, cfg: Option<AgentToolConfig>) -> Arc<dyn Tool> {
58        Arc::new(AgentTool {
59            agent,
60            skip_summarization: cfg.is_some_and(|c| c.skip_summarization),
61        })
62    }
63}
64
65/// The error of [`AgentTool`]'s run: "<message>: <source>", so a caller can
66/// find the wrapped error (e.g. `AgentError::LlmCallsLimitExceeded`) in the source chain.
67#[derive(Debug)]
68struct AgentToolError {
69    message: String,
70    source: Option<Box<dyn std::error::Error + Send + Sync>>,
71}
72
73impl std::fmt::Display for AgentToolError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match &self.source {
76            Some(s) => write!(f, "{}: {}", self.message, s),
77            None => f.write_str(&self.message),
78        }
79    }
80}
81
82impl std::error::Error for AgentToolError {
83    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84        self.source
85            .as_deref()
86            .map(|s| s as &(dyn std::error::Error + 'static))
87    }
88}
89
90fn exec(message: String) -> ToolError {
91    ToolError::Execution(Box::new(AgentToolError {
92        message,
93        source: None,
94    }))
95}
96
97fn exec_src(
98    message: String,
99    source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
100) -> ToolError {
101    ToolError::Execution(Box::new(AgentToolError {
102        message,
103        source: Some(source.into()),
104    }))
105}
106
107impl Tool for AgentTool {
108    fn name(&self) -> &str {
109        self.agent.name()
110    }
111
112    fn description(&self) -> &str {
113        self.agent.description()
114    }
115
116    /// The agent's function declaration (see `make_function_declaration`).
117    fn declaration(&self) -> Option<FunctionDeclaration> {
118        Some(make_function_declaration(&*self.agent))
119    }
120
121    // `process_request` is not overridden: its job is `pack_tool`, which the
122    // flow runs via `gadk_agent::pack_tool` before calling `Tool::process_request`.
123
124    fn as_runnable(&self) -> Option<&dyn RunnableTool> {
125        Some(self)
126    }
127
128    /// With skip summarization the sub-agent's result is the
129    /// final answer, so it is still shown to the user.
130    fn display_result_on_skip_summarization(&self) -> bool {
131        true
132    }
133
134    /// Classified as `SubAgent` (`A2A` when its agent is remote).
135    fn origin_kind(&self) -> ToolOriginKind {
136        ToolOriginKind::SubAgent
137    }
138
139    /// The wrapped agent.
140    fn origin_agent(&self) -> Option<Arc<dyn Agent>> {
141        Some(self.agent.clone())
142    }
143
144    fn as_any(&self) -> &dyn Any {
145        self
146    }
147}
148
149/// The text of one part of the sub-agent's last content: non-empty text, else a non-empty code
150/// execution output without trailing newlines, else executable code, in that order.
151fn part_text(p: &gadk_genai::Part) -> String {
152    if !p.text.is_empty() {
153        p.text.clone()
154    } else if let Some(r) = p
155        .code_execution_result
156        .as_ref()
157        .filter(|r| !r.output.is_empty())
158    {
159        r.output.trim_end_matches('\n').to_string()
160    } else if let Some(c) = &p.executable_code {
161        c.code.clone()
162    } else {
163        String::new()
164    }
165}
166
167#[async_trait]
168impl RunnableTool for AgentTool {
169    /// Runs the wrapped agent in a child runner and returns its final answer under `result`.
170    async fn run(&self, ctx: Context, args: Value) -> Result<Map<String, Value>, ToolError> {
171        let name = self.agent.name().to_string();
172        let margs = match args {
173            Value::Object(m) => m,
174            other => {
175                return Err(ToolError::InvalidArgument(format!(
176                    "agentTool expects map[string]any arguments, got {}",
177                    go_type_name(&other)
178                )));
179            }
180        };
181
182        // The same lookup as the declaration (`make_function_declaration`), so a
183        // workflow agent takes the arguments of its first sub-agent's input schema. The output
184        // schema is an LLM agent's own only. Cloned so no borrow of the agent state is held
185        // across an await.
186        let input_schema = input_schema_of(&*self.agent);
187        let output_schema = reveal(&*self.agent).and_then(|s| s.cfg.output_schema.clone());
188
189        let content = match &input_schema {
190            Some(schema) => {
191                validate_map_on_schema(&margs, schema, true).map_err(|e| {
192                    exec(format!("argument validation failed for agent {name}: {e}"))
193                })?;
194                // Compact JSON with sorted keys and HTML escaping ([`go_json_marshal`]); it cannot
195                // fail on a JSON map, so there is no "error serializing tool arguments" branch.
196                let json = go_json_marshal(&Value::Object(margs));
197                Content::from_text(json, ROLE_USER)
198            }
199            None => {
200                let input = margs.get("request").ok_or_else(|| {
201                    exec(format!(
202                        "missing required argument 'request' for agent {name}"
203                    ))
204                })?;
205                // The string as is, else the display form of the JSON-decoded value.
206                Content::from_text(go_sprint(&as_go_floats(input)), ROLE_USER)
207            }
208        };
209
210        // Set only once the input is valid, so an argument error goes back to the parent model
211        // instead of ending its turn.
212        if self.skip_summarization {
213            ctx.update_actions(|a| a.skip_summarization = true);
214        }
215
216        let session_service: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
217        let runner = Runner::new(RunnerConfig {
218            app_name: name.clone(),
219            agent: self.agent.clone(),
220            session_service: session_service.clone(),
221            artifact_service: Some(new_forwarding_service(ctx.artifacts())),
222            memory_service: Some(Arc::new(gadk_memory::InMemoryMemoryService::new())),
223            plugin_config: PluginConfig::default(),
224            auto_create_session: false,
225            platform: ctx.platform().clone(),
226            compaction: None,
227        })
228        .map_err(|e| exec_src(format!("failed to create runner for agent {name}"), e))?;
229
230        // Filter out ADK-internal state.
231        let state: Map<String, Value> = ctx
232            .state()
233            .all()
234            .into_iter()
235            .filter(|(k, _)| !k.starts_with("_adk"))
236            .collect();
237        let sub_session = session_service
238            .create(CreateRequest {
239                app_name: name.clone(),
240                user_id: ctx.user_id().to_string(),
241                session_id: None,
242                state: Some(state),
243            })
244            .await
245            .map_err(|e| exec_src(format!("failed to create session for sub-agent {name}"), e))?;
246
247        // Forward the caller's already-resolved model-call budget;
248        let max_llm_calls = ctx.llm_call_limiter().map_or(0, |l| l.max_llm_calls());
249        let run_cfg = RunConfig {
250            streaming_mode: StreamingMode::Sse,
251            max_llm_calls,
252            ..Default::default()
253        };
254        // Dropping the stream (on return) cancels the child invocation. The sub-runner starts
255        // with a context marked to inherit this invocation's plugins
256        // (`with_inherited_plugins`), which a plugin-less runner keeps.
257        let mut events = runner.run_with_context(
258            &ctx.as_invocation().with_inherited_plugins(),
259            sub_session.user_id(),
260            sub_session.id(),
261            Some(content),
262            run_cfg,
263            RunOptions::default(),
264        );
265        let mut last_content: Option<Content> = None;
266        // Long-running calls that are never answered before the run ends (e.g. a tool
267        // confirmation) leave the sub-agent paused. Its session is discarded, so the pause can
268        // never be resumed.
269        let mut pending_ids: BTreeSet<String> = BTreeSet::new();
270        loop {
271            // The caller's context is the child's context: cancelling the caller cancels
272            // the child.
273            let next = tokio::select! {
274                biased;
275                _ = ctx.cancellation_token().cancelled() => {
276                    return Err(exec_src(
277                        format!("error during execution of sub-agent {name}"),
278                        AgentError::Cancelled,
279                    ));
280                }
281                n = events.next() => n,
282            };
283            let Some(item) = next else { break };
284            let event = item
285                .map_err(|e| exec_src(format!("error during execution of sub-agent {name}"), e))?;
286            let (code, message) = (&event.response.error_code, &event.response.error_message);
287            if !code.is_empty() || !message.is_empty() {
288                return Err(exec(format!(
289                    "error from sub-agent {} (code: {}, message: {})",
290                    go_quote(&name),
291                    go_quote(code),
292                    go_quote(message)
293                )));
294            }
295            // Partial chunks carry IDs the flow never acts on; a streamed call gets its final
296            // ID only on the aggregated event.
297            if !event.response.partial {
298                pending_ids.extend(event.long_running_tool_ids.iter().cloned());
299                if let Some(c) = &event.response.content {
300                    for fr in c.parts.iter().filter_map(|p| p.function_response.as_ref()) {
301                        pending_ids.remove(&fr.id);
302                    }
303                }
304            }
305            if let Some(c) = event.response.content {
306                last_content = Some(c);
307            }
308        }
309
310        if !pending_ids.is_empty() {
311            // The parent model must see this error, so don't end its turn here, whatever set
312            // skip_summarization on this call.
313            ctx.update_actions(|a| a.skip_summarization = false);
314            return Err(exec(format!(
315                "sub-agent {} stopped waiting on unresolved long-running tool calls [{}], which AgentTool cannot resume",
316                go_quote(&name),
317                pending_ids.into_iter().collect::<Vec<_>>().join(" ")
318            )));
319        }
320
321        // An empty reply is the result "" (also with an output schema: there is
322        // nothing to validate).
323        let empty_result =
324            || Map::from_iter([("result".to_string(), Value::String(String::new()))]);
325        let Some(last) = last_content else {
326            return Ok(empty_result());
327        };
328        let output_text = last
329            .parts
330            .iter()
331            .filter(|p| !p.thought)
332            .map(part_text)
333            .filter(|t| !t.is_empty())
334            .collect::<Vec<_>>()
335            .join("\n");
336        if output_text.is_empty() {
337            return Ok(empty_result());
338        }
339        if let Some(schema) = &output_schema {
340            return validate_output_schema(&output_text, schema).map_err(|e| {
341                exec(format!(
342                    "output validation failed for sub-agent {name}: {e}"
343                ))
344            });
345        }
346        let mut out = Map::new();
347        out.insert("result".to_string(), Value::String(output_text));
348        Ok(out)
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use serde_json::json;
355
356    use super::*;
357    use crate::llm::{LlmAgentConfig, agent as llm_agent};
358    use crate::testutil::MockModel;
359
360    /// The child's user message for a non-string `request` is Go `fmt.Sprint` of the JSON-decoded
361    /// (float64) value; expected texts checked against Go.
362    #[tokio::test]
363    async fn non_string_request_is_go_sprint_of_float64() {
364        let cases = [
365            (json!(1000000), "1e+06"),
366            (json!({"n": 5}), "map[n:5]"),
367            (json!(2.5), "2.5"),
368            (json!([1, 1e21, true, null]), "[1 1e+21 true <nil>]"),
369        ];
370        for (request, want) in cases {
371            let model = MockModel::from_contents(vec![Content::from_text("ok", "model")]);
372            let agent = llm_agent::new(LlmAgentConfig {
373                name: "child".into(),
374                model: Some(model.clone()),
375                ..Default::default()
376            })
377            .unwrap();
378            let sess = InMemorySessionService::new()
379                .create(CreateRequest {
380                    app_name: "app".into(),
381                    user_id: "user".into(),
382                    ..Default::default()
383                })
384                .await
385                .unwrap();
386            let ctx = Context::builder().session(sess).build();
387            AgentTool::new(agent, None)
388                .as_runnable()
389                .unwrap()
390                .run(ctx, json!({ "request": request }))
391                .await
392                .unwrap();
393            let reqs = model.requests();
394            let user = reqs[0]
395                .contents
396                .iter()
397                .find(|c| c.role == ROLE_USER)
398                .expect("child user message");
399            assert_eq!(user.parts[0].text, want, "request {request}");
400        }
401    }
402}
403
404#[cfg(test)]
405#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
406mod origin_tests {
407    use super::*;
408    use crate::llm::{LlmAgentConfig, agent as llm_agent};
409
410    #[test]
411    fn agent_tool_is_a_sub_agent_tool_of_its_agent() {
412        let agent = llm_agent::new(LlmAgentConfig {
413            name: "child".into(),
414            ..Default::default()
415        })
416        .unwrap();
417        let t = AgentTool::new(agent.clone(), None);
418        assert_eq!(t.origin_kind(), ToolOriginKind::SubAgent);
419        assert!(Arc::ptr_eq(&t.origin_agent().unwrap(), &agent));
420        let agents = t.origin_agents();
421        assert_eq!(agents.len(), 1);
422        assert!(Arc::ptr_eq(&agents[0], &agent));
423        assert!(t.unwrap().is_none());
424    }
425}