Skip to main content

adk_tool/builtin/
gemini_extra.rs

1use crate::builtin::bypass::BypassMultiToolsLimit;
2use adk_core::{Result, Tool, ToolContext, ToolEffect};
3use async_trait::async_trait;
4use serde_json::{Value, json};
5use std::sync::Arc;
6
7/// Contextual Google Maps location used by Gemini retrieval config.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub struct GoogleMapsContext {
10    latitude: f64,
11    longitude: f64,
12}
13
14impl GoogleMapsContext {
15    /// Create a new contextual location.
16    pub fn new(latitude: f64, longitude: f64) -> Self {
17        Self { latitude, longitude }
18    }
19
20    fn to_json(self) -> Value {
21        json!({
22            "retrievalConfig": {
23                "latLng": {
24                    "latitude": self.latitude,
25                    "longitude": self.longitude,
26                }
27            }
28        })
29    }
30}
31
32/// Gemini built-in Google Maps grounding tool.
33#[derive(Debug, Clone, Default)]
34pub struct GoogleMapsTool {
35    enable_widget: bool,
36    context: Option<GoogleMapsContext>,
37}
38
39impl GoogleMapsTool {
40    /// Create a new `GoogleMapsTool` with default settings.
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// Enable or disable the interactive widget in the response.
46    pub fn with_widget(mut self, enable_widget: bool) -> Self {
47        self.enable_widget = enable_widget;
48        self
49    }
50
51    /// Set the contextual location for map queries.
52    pub fn with_context(mut self, context: GoogleMapsContext) -> Self {
53        self.context = Some(context);
54        self
55    }
56}
57
58#[async_trait]
59impl Tool for GoogleMapsTool {
60    fn name(&self) -> &str {
61        "google_maps"
62    }
63
64    fn description(&self) -> &str {
65        "Grounds responses with Google Maps data for places, routes, and local context."
66    }
67
68    fn is_builtin(&self) -> bool {
69        true
70    }
71
72    // Runs on the provider; a policy sees this effect before the tool is attached.
73    fn effect(&self) -> ToolEffect {
74        ToolEffect::ReadOnly
75    }
76
77    fn declaration(&self) -> Value {
78        json!({
79            "name": self.name(),
80            "description": self.description(),
81            "x-adk-gemini-tool": {
82                "google_maps": {
83                    "enable_widget": self.enable_widget.then_some(true),
84                }
85            },
86            "x-adk-gemini-tool-config": self.context.map(GoogleMapsContext::to_json),
87        })
88    }
89
90    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
91        Err(adk_core::AdkError::tool("GoogleMaps is handled internally by Gemini"))
92    }
93}
94
95/// Gemini built-in code execution tool.
96#[derive(Debug, Clone, Default)]
97pub struct GeminiCodeExecutionTool;
98
99impl GeminiCodeExecutionTool {
100    /// Create a new `GeminiCodeExecutionTool`.
101    pub fn new() -> Self {
102        Self
103    }
104}
105
106#[async_trait]
107impl Tool for GeminiCodeExecutionTool {
108    fn name(&self) -> &str {
109        "gemini_code_execution"
110    }
111
112    fn description(&self) -> &str {
113        "Allows Gemini to write and execute Python code server-side."
114    }
115
116    fn is_builtin(&self) -> bool {
117        true
118    }
119
120    // Runs or acts outside the agent; never assumed safe to repeat.
121    fn effect(&self) -> ToolEffect {
122        ToolEffect::NonIdempotent
123    }
124
125    fn declaration(&self) -> Value {
126        json!({
127            "name": self.name(),
128            "description": self.description(),
129            "x-adk-gemini-tool": {
130                "code_execution": {}
131            }
132        })
133    }
134
135    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
136        Err(adk_core::AdkError::tool("Gemini code execution is handled internally by Gemini"))
137    }
138}
139
140/// Gemini built-in file search tool.
141#[derive(Debug, Clone)]
142pub struct GeminiFileSearchTool {
143    file_search_store_names: Vec<String>,
144}
145
146impl GeminiFileSearchTool {
147    /// Create a new `GeminiFileSearchTool` with the given store names.
148    pub fn new(file_search_store_names: impl IntoIterator<Item = impl Into<String>>) -> Self {
149        Self {
150            file_search_store_names: file_search_store_names.into_iter().map(Into::into).collect(),
151        }
152    }
153}
154
155#[async_trait]
156impl Tool for GeminiFileSearchTool {
157    fn name(&self) -> &str {
158        "gemini_file_search"
159    }
160
161    fn description(&self) -> &str {
162        "Searches Gemini File Search stores for relevant documents."
163    }
164
165    fn is_builtin(&self) -> bool {
166        true
167    }
168
169    // Runs on the provider; a policy sees this effect before the tool is attached.
170    fn effect(&self) -> ToolEffect {
171        ToolEffect::ReadOnly
172    }
173
174    fn declaration(&self) -> Value {
175        json!({
176            "name": self.name(),
177            "description": self.description(),
178            "x-adk-gemini-tool": {
179                "file_search": {
180                    "file_search_store_names": self.file_search_store_names
181                }
182            }
183        })
184    }
185
186    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
187        Err(adk_core::AdkError::tool("Gemini file search is handled internally by Gemini"))
188    }
189}
190
191/// Bypass support: convert the built-in Gemini File Search tool into a
192/// function-calling tool so it can be used alongside custom function tools
193/// under the Gemini Interactions API.
194///
195/// The converted tool declares a `query: string` function schema and performs
196/// the document search by delegating to an internal single-turn agent (an
197/// `LlmAgent` configured with [`GeminiFileSearchTool`] and a Gemini model).
198///
199/// # Example
200///
201/// ```rust,ignore
202/// use adk_tool::{BypassMultiToolsLimit, GeminiFileSearchTool};
203/// use std::sync::Arc;
204///
205/// // `file_search_agent` is an LlmAgent with GeminiFileSearchTool + a Gemini model.
206/// let tool = GeminiFileSearchTool::new(["my-store"])
207///     .with_bypass_multi_tools_limit(Arc::new(file_search_agent));
208/// assert!(!tool.is_builtin());
209/// ```
210impl BypassMultiToolsLimit for GeminiFileSearchTool {
211    fn bypass_name(&self) -> String {
212        self.name().to_string()
213    }
214
215    fn bypass_description(&self) -> String {
216        "Searches Gemini File Search stores for documents relevant to a query.".to_string()
217    }
218
219    fn bypass_parameters_schema(&self) -> Value {
220        json!({
221            "type": "object",
222            "properties": {
223                "query": {
224                    "type": "string",
225                    "description": "The query used to search the File Search stores."
226                }
227            },
228            "required": ["query"]
229        })
230    }
231
232    fn bypass_query_field(&self) -> String {
233        "query".to_string()
234    }
235}
236
237/// Target environment for Gemini computer use.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum GeminiComputerEnvironment {
240    /// Browser-based environment.
241    Browser,
242}
243
244impl GeminiComputerEnvironment {
245    fn as_wire(self) -> &'static str {
246        match self {
247            Self::Browser => "ENVIRONMENT_BROWSER",
248        }
249    }
250}
251
252/// Gemini built-in computer use tool declaration.
253#[derive(Debug, Clone)]
254pub struct GeminiComputerUseTool {
255    environment: GeminiComputerEnvironment,
256    excluded_predefined_functions: Vec<String>,
257}
258
259impl Default for GeminiComputerUseTool {
260    fn default() -> Self {
261        Self {
262            environment: GeminiComputerEnvironment::Browser,
263            excluded_predefined_functions: Vec::new(),
264        }
265    }
266}
267
268impl GeminiComputerUseTool {
269    /// Create a new `GeminiComputerUseTool` for the given environment.
270    pub fn new(environment: GeminiComputerEnvironment) -> Self {
271        Self { environment, ..Default::default() }
272    }
273
274    /// Exclude specific predefined functions from computer use.
275    pub fn with_excluded_functions(
276        mut self,
277        excluded_predefined_functions: impl IntoIterator<Item = impl Into<String>>,
278    ) -> Self {
279        self.excluded_predefined_functions =
280            excluded_predefined_functions.into_iter().map(Into::into).collect();
281        self
282    }
283}
284
285#[async_trait]
286impl Tool for GeminiComputerUseTool {
287    fn name(&self) -> &str {
288        "gemini_computer_use"
289    }
290
291    fn description(&self) -> &str {
292        "Enables Gemini computer use, which emits predefined UI action function calls."
293    }
294
295    fn is_builtin(&self) -> bool {
296        true
297    }
298
299    // Runs or acts outside the agent; never assumed safe to repeat.
300    fn effect(&self) -> ToolEffect {
301        ToolEffect::NonIdempotent
302    }
303
304    fn declaration(&self) -> Value {
305        json!({
306            "name": self.name(),
307            "description": self.description(),
308            "x-adk-gemini-tool": {
309                "computer_use": {
310                    "environment": self.environment.as_wire(),
311                    "excluded_predefined_functions": (!self.excluded_predefined_functions.is_empty())
312                        .then_some(self.excluded_predefined_functions.clone()),
313                }
314            }
315        })
316    }
317
318    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
319        Err(adk_core::AdkError::tool("Gemini computer use actions must be executed client-side"))
320    }
321}