Skip to main content

gadk_engine/tool/
streaming_function.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//! The streaming function tool: a tool wrapping a function that returns a stream of text chunks.
17
18use std::any::Any;
19use std::panic::AssertUnwindSafe;
20use std::sync::Arc;
21
22use futures::stream::BoxStream;
23use futures::{StreamExt, future, stream};
24use gadk_agent::{Context, StreamingTool, Tool, ToolError, ToolOriginKind};
25use gadk_genai::FunctionDeclaration;
26use serde_json::Value;
27
28use crate::tool::function::{
29    FunctionToolConfig, check_args_type, check_args_value, check_confirmation, declaration,
30    resolved_schema,
31};
32use crate::tool::utils::{CompiledSchema, convert_args_with_schema, infer_schema, panic_message};
33
34type ErasedStart = Arc<
35    dyn Fn(Context, Value) -> Result<BoxStream<'static, Result<String, ToolError>>, ToolError>
36        + Send
37        + Sync,
38>;
39
40/// A tool wrapping a Rust function that returns a stream of
41/// text chunks.
42pub struct StreamingFunctionTool {
43    cfg: FunctionToolConfig,
44    input_schema: Arc<CompiledSchema>,
45    start: ErasedStart,
46}
47
48impl StreamingFunctionTool {
49    /// Wraps the streaming handler `f`.
50    ///
51    /// Fails with [`ToolError::InvalidArgument`] when `Args` is not an object type or the input schema cannot
52    /// be compiled.
53    #[allow(clippy::new_ret_no_self)] // returns the tool as `Arc<dyn Tool>`
54    pub fn new<Args, F, S>(cfg: FunctionToolConfig, f: F) -> Result<Arc<dyn Tool>, ToolError>
55    where
56        Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
57        F: Fn(Context, Args) -> S + Send + Sync + 'static,
58        S: futures::Stream<Item = Result<String, ToolError>> + Send + 'static,
59    {
60        Self::build::<Args, F, S, fn(&Args) -> bool>(cfg, f, None)
61    }
62
63    /// Like [`StreamingFunctionTool::new`], with a confirmation provider: when the call
64    /// carries no confirmation, `provider(&args)` decides whether one is required, overriding
65    /// `cfg.require_confirmation`.
66    pub fn with_confirmation_provider<Args, F, S, P>(
67        cfg: FunctionToolConfig,
68        f: F,
69        provider: P,
70    ) -> Result<Arc<dyn Tool>, ToolError>
71    where
72        Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
73        F: Fn(Context, Args) -> S + Send + Sync + 'static,
74        S: futures::Stream<Item = Result<String, ToolError>> + Send + 'static,
75        P: Fn(&Args) -> bool + Send + Sync + 'static,
76    {
77        Self::build(cfg, f, Some(provider))
78    }
79
80    fn build<Args, F, S, P>(
81        cfg: FunctionToolConfig,
82        f: F,
83        provider: Option<P>,
84    ) -> Result<Arc<dyn Tool>, ToolError>
85    where
86        Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
87        F: Fn(Context, Args) -> S + Send + Sync + 'static,
88        S: futures::Stream<Item = Result<String, ToolError>> + Send + 'static,
89        P: Fn(&Args) -> bool + Send + Sync + 'static,
90    {
91        check_args_type::<Args>()?;
92        let input_schema = Arc::new(resolved_schema(
93            cfg.input_schema.as_ref(),
94            infer_schema::<Args>,
95            "input",
96        )?);
97
98        let name = cfg.name.clone();
99        let require_confirmation = cfg.require_confirmation;
100        let schema = input_schema.clone();
101        // The synchronous prelude of a run: argument checks, conversion, confirmation, handler
102        // call.
103        let start: ErasedStart = Arc::new(move |ctx: Context, args: Value| {
104            check_args_value(&args)?;
105            let input: Args = convert_args_with_schema(&args, Some(&schema))
106                .map_err(ToolError::InvalidArgument)?;
107            check_confirmation(&ctx, &name, || {
108                provider
109                    .as_ref()
110                    .map_or(require_confirmation, |p| p(&input))
111            })?;
112            Ok(f(ctx, input).boxed())
113        });
114        Ok(Arc::new(StreamingFunctionTool {
115            cfg,
116            input_schema,
117            start,
118        }))
119    }
120}
121
122impl Tool for StreamingFunctionTool {
123    fn name(&self) -> &str {
124        &self.cfg.name
125    }
126
127    fn description(&self) -> &str {
128        &self.cfg.description
129    }
130
131    fn is_long_running(&self) -> bool {
132        self.cfg.is_long_running
133    }
134
135    fn declaration(&self) -> Option<FunctionDeclaration> {
136        Some(declaration(&self.cfg, &self.input_schema, None))
137    }
138
139    // `process_request` is deliberately not overridden: its job is `pack_tool`, which
140    // the flow runs via `gadk_agent::pack_tool` before calling `Tool::process_request`.
141
142    fn as_streaming(&self) -> Option<&dyn StreamingTool> {
143        Some(self)
144    }
145
146    /// [`FunctionToolConfig::origin`] (default [`ToolOriginKind::Local`]: a streaming function
147    /// tool is a function tool too).
148    fn origin_kind(&self) -> ToolOriginKind {
149        self.cfg.origin
150    }
151
152    fn as_any(&self) -> &dyn Any {
153        self
154    }
155}
156
157impl StreamingTool for StreamingFunctionTool {
158    /// Runs the handler and streams its chunks.
159    /// - Lazy: nothing runs until the first poll.
160    /// - A panic while calling the handler or while polling its stream becomes one final
161    ///   `ToolError::Panic` item (text `panic in tool "<name>": <message>`), after which the stream
162    ///   ends.
163    /// - Dropping the returned stream drops the handler's stream, which stops the handler.
164    /// - Consumer panics and panics raised while *dropping* the handler stream are never caught:
165    ///   the consumer is not called from inside this stream, and Drop is outside catch_unwind's
166    ///   poll scope, so consumer panics propagate.
167    fn run_stream(
168        &self,
169        ctx: Context,
170        args: Value,
171    ) -> BoxStream<'static, Result<String, ToolError>> {
172        let start = self.start.clone();
173        let name = self.cfg.name.clone();
174        let body =
175            stream::once(async move { start(ctx, args) }).flat_map(|prelude| match prelude {
176                Ok(s) => s,
177                Err(e) => stream::once(future::ready(Err(e))).boxed(),
178            });
179        AssertUnwindSafe(body)
180            .catch_unwind()
181            .map(move |item| match item {
182                Ok(item) => item,
183                Err(payload) => Err(ToolError::Panic(format!(
184                    "panic in tool {}: {}",
185                    gadk_agent::go_quote(&name),
186                    panic_message(&*payload)
187                ))),
188            })
189            .boxed()
190    }
191}
192
193#[cfg(test)]
194#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
195mod origin_tests {
196    use super::*;
197
198    #[derive(serde::Deserialize, schemars::JsonSchema)]
199    struct NoArgs {}
200
201    fn tool(cfg: FunctionToolConfig) -> Arc<dyn Tool> {
202        StreamingFunctionTool::new(cfg, |_ctx: Context, _args: NoArgs| {
203            stream::empty::<Result<String, ToolError>>()
204        })
205        .unwrap()
206    }
207
208    #[test]
209    fn streaming_function_tool_reports_its_configured_origin() {
210        let local = tool(FunctionToolConfig::new("s", ""));
211        assert_eq!(local.origin_kind(), ToolOriginKind::Local);
212        assert!(local.origin_agent().is_none());
213        let skill = tool(FunctionToolConfig {
214            origin: ToolOriginKind::Skill,
215            ..FunctionToolConfig::new("s", "")
216        });
217        assert_eq!(skill.origin_kind(), ToolOriginKind::Skill);
218    }
219}