1use 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
40pub struct StreamingFunctionTool {
43 cfg: FunctionToolConfig,
44 input_schema: Arc<CompiledSchema>,
45 start: ErasedStart,
46}
47
48impl StreamingFunctionTool {
49 #[allow(clippy::new_ret_no_self)] 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 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 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 fn as_streaming(&self) -> Option<&dyn StreamingTool> {
143 Some(self)
144 }
145
146 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 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}