Skip to main content

gemini_adk_rs/tool/
simple.rs

1//! Simple function tool that wraps an async closure.
2
3use async_trait::async_trait;
4
5use crate::BoxFuture;
6use crate::error::ToolError;
7
8use super::ToolFunction;
9
10/// Async handler over raw JSON arguments.
11type ToolHandler =
12    Box<dyn Fn(serde_json::Value) -> BoxFuture<Result<serde_json::Value, ToolError>> + Send + Sync>;
13
14/// Simple function tool that wraps an async closure.
15pub struct SimpleTool {
16    name: String,
17    description: String,
18    parameters: Option<serde_json::Value>,
19    handler: ToolHandler,
20}
21
22impl SimpleTool {
23    /// Create a new simple function tool.
24    ///
25    /// # Examples
26    ///
27    /// ```rust,ignore
28    /// use gemini_adk_rs::tool::SimpleTool;
29    /// use serde_json::json;
30    ///
31    /// let tool = SimpleTool::new(
32    ///     "greet",
33    ///     "Greet a user by name",
34    ///     Some(json!({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]})),
35    ///     |args| async move {
36    ///         let name = args["name"].as_str().unwrap_or("World");
37    ///         Ok(json!({"greeting": format!("Hello, {name}!")}))
38    ///     },
39    /// );
40    /// ```
41    pub fn new<F, Fut>(
42        name: impl Into<String>,
43        description: impl Into<String>,
44        parameters: Option<serde_json::Value>,
45        handler: F,
46    ) -> Self
47    where
48        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
49        Fut: std::future::Future<Output = Result<serde_json::Value, ToolError>> + Send + 'static,
50    {
51        Self {
52            name: name.into(),
53            description: description.into(),
54            parameters,
55            handler: Box::new(move |args| Box::pin(handler(args))),
56        }
57    }
58}
59
60#[async_trait]
61impl ToolFunction for SimpleTool {
62    fn name(&self) -> &str {
63        &self.name
64    }
65    fn description(&self) -> &str {
66        &self.description
67    }
68    fn parameters(&self) -> Option<serde_json::Value> {
69        self.parameters.clone()
70    }
71    async fn call(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
72        (self.handler)(args).await
73    }
74}