Skip to main content

adk_tool/builtin/
openai.rs

1use adk_core::{Result, Tool, ToolContext, ToolEffect};
2use async_trait::async_trait;
3use serde_json::{Map, Value, json};
4use std::sync::Arc;
5
6/// Approximate user location for OpenAI web search.
7#[derive(Debug, Clone, Default)]
8pub struct OpenAIApproximateLocation {
9    city: Option<String>,
10    country: Option<String>,
11    region: Option<String>,
12    timezone: Option<String>,
13}
14
15impl OpenAIApproximateLocation {
16    /// Create a new empty approximate location.
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Set the city name.
22    pub fn with_city(mut self, city: impl Into<String>) -> Self {
23        self.city = Some(city.into());
24        self
25    }
26
27    /// Set the country name.
28    pub fn with_country(mut self, country: impl Into<String>) -> Self {
29        self.country = Some(country.into());
30        self
31    }
32
33    /// Set the region name.
34    pub fn with_region(mut self, region: impl Into<String>) -> Self {
35        self.region = Some(region.into());
36        self
37    }
38
39    /// Set the timezone identifier.
40    pub fn with_timezone(mut self, timezone: impl Into<String>) -> Self {
41        self.timezone = Some(timezone.into());
42        self
43    }
44
45    fn to_json(&self) -> Value {
46        json!({
47            "type": "approximate",
48            "city": self.city,
49            "country": self.country,
50            "region": self.region,
51            "timezone": self.timezone,
52        })
53    }
54}
55
56/// OpenAI web search tool flavor.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum OpenAIWebSearchVariant {
59    #[default]
60    Stable,
61    Preview20250311,
62}
63
64impl OpenAIWebSearchVariant {
65    fn as_wire(self) -> &'static str {
66        match self {
67            Self::Stable => "web_search",
68            Self::Preview20250311 => "web_search_preview_2025_03_11",
69        }
70    }
71}
72
73/// OpenAI hosted web search tool.
74#[derive(Debug, Clone, Default)]
75pub struct OpenAIWebSearchTool {
76    variant: OpenAIWebSearchVariant,
77    allowed_domains: Option<Vec<String>>,
78    user_location: Option<OpenAIApproximateLocation>,
79    search_context_size: Option<String>,
80}
81
82impl OpenAIWebSearchTool {
83    /// Create a new `OpenAIWebSearchTool` with default (stable) variant.
84    pub fn new() -> Self {
85        Self::default()
86    }
87
88    /// Use the preview variant of the web search tool.
89    pub fn preview(mut self) -> Self {
90        self.variant = OpenAIWebSearchVariant::Preview20250311;
91        self
92    }
93
94    /// Restrict search results to the specified domains.
95    pub fn with_allowed_domains(
96        mut self,
97        domains: impl IntoIterator<Item = impl Into<String>>,
98    ) -> Self {
99        self.allowed_domains = Some(domains.into_iter().map(Into::into).collect());
100        self
101    }
102
103    /// Set the approximate user location for localized results.
104    pub fn with_user_location(mut self, user_location: OpenAIApproximateLocation) -> Self {
105        self.user_location = Some(user_location);
106        self
107    }
108
109    /// Set the search context size (e.g., "low", "medium", "high").
110    pub fn with_search_context_size(mut self, size: impl Into<String>) -> Self {
111        self.search_context_size = Some(size.into());
112        self
113    }
114
115    fn tool_json(&self) -> Value {
116        json!({
117            "type": self.variant.as_wire(),
118            "filters": self.allowed_domains.as_ref().map(|domains| json!({ "allowed_domains": domains })),
119            "user_location": self.user_location.as_ref().map(OpenAIApproximateLocation::to_json),
120            "search_context_size": self.search_context_size,
121        })
122    }
123}
124
125#[async_trait]
126impl Tool for OpenAIWebSearchTool {
127    fn name(&self) -> &str {
128        "openai_web_search"
129    }
130
131    fn description(&self) -> &str {
132        "Uses OpenAI hosted web search to retrieve current web information."
133    }
134
135    fn is_builtin(&self) -> bool {
136        true
137    }
138
139    // Runs on the provider; a policy sees this effect before the tool is attached.
140    fn effect(&self) -> ToolEffect {
141        ToolEffect::ReadOnly
142    }
143
144    fn declaration(&self) -> Value {
145        json!({
146            "name": self.name(),
147            "description": self.description(),
148            "x-adk-openai-tool": self.tool_json(),
149        })
150    }
151
152    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
153        Err(adk_core::AdkError::tool("OpenAI web search is handled by the Responses API"))
154    }
155}
156
157/// OpenAI hosted file search tool.
158#[derive(Debug, Clone)]
159pub struct OpenAIFileSearchTool {
160    vector_store_ids: Vec<String>,
161    max_num_results: Option<u32>,
162    filters: Option<Value>,
163    ranking_options: Option<Value>,
164}
165
166impl OpenAIFileSearchTool {
167    /// Create a new `OpenAIFileSearchTool` with the given vector store IDs.
168    pub fn new(vector_store_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
169        Self {
170            vector_store_ids: vector_store_ids.into_iter().map(Into::into).collect(),
171            max_num_results: None,
172            filters: None,
173            ranking_options: None,
174        }
175    }
176
177    /// Set the maximum number of results to return.
178    pub fn with_max_num_results(mut self, max_num_results: u32) -> Self {
179        self.max_num_results = Some(max_num_results);
180        self
181    }
182
183    /// Set metadata filters for the search.
184    pub fn with_filters(mut self, filters: Value) -> Self {
185        self.filters = Some(filters);
186        self
187    }
188
189    /// Set ranking options for result ordering.
190    pub fn with_ranking_options(mut self, ranking_options: Value) -> Self {
191        self.ranking_options = Some(ranking_options);
192        self
193    }
194
195    fn tool_json(&self) -> Value {
196        json!({
197            "type": "file_search",
198            "vector_store_ids": self.vector_store_ids,
199            "max_num_results": self.max_num_results,
200            "filters": self.filters,
201            "ranking_options": self.ranking_options,
202        })
203    }
204}
205
206#[async_trait]
207impl Tool for OpenAIFileSearchTool {
208    fn name(&self) -> &str {
209        "openai_file_search"
210    }
211
212    fn description(&self) -> &str {
213        "Uses OpenAI hosted file search against one or more vector stores."
214    }
215
216    fn is_builtin(&self) -> bool {
217        true
218    }
219
220    // Runs on the provider; a policy sees this effect before the tool is attached.
221    fn effect(&self) -> ToolEffect {
222        ToolEffect::ReadOnly
223    }
224
225    fn declaration(&self) -> Value {
226        json!({
227            "name": self.name(),
228            "description": self.description(),
229            "x-adk-openai-tool": self.tool_json(),
230        })
231    }
232
233    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
234        Err(adk_core::AdkError::tool("OpenAI file search is handled by the Responses API"))
235    }
236}
237
238/// OpenAI hosted code interpreter tool.
239#[derive(Debug, Clone, Default)]
240pub struct OpenAICodeInterpreterTool {
241    file_ids: Vec<String>,
242    memory_limit: Option<u64>,
243    container_id: Option<String>,
244}
245
246impl OpenAICodeInterpreterTool {
247    /// Create a new `OpenAICodeInterpreterTool` with default settings.
248    pub fn new() -> Self {
249        Self::default()
250    }
251
252    /// Attach file IDs to the code interpreter container.
253    pub fn with_file_ids(mut self, file_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
254        self.file_ids = file_ids.into_iter().map(Into::into).collect();
255        self
256    }
257
258    /// Set the memory limit in bytes for the container.
259    pub fn with_memory_limit(mut self, memory_limit: u64) -> Self {
260        self.memory_limit = Some(memory_limit);
261        self
262    }
263
264    /// Use a specific container ID instead of auto-provisioning.
265    pub fn with_container_id(mut self, container_id: impl Into<String>) -> Self {
266        self.container_id = Some(container_id.into());
267        self
268    }
269
270    fn tool_json(&self) -> Value {
271        let container = if let Some(container_id) = &self.container_id {
272            Value::String(container_id.clone())
273        } else {
274            json!({
275                "type": "auto",
276                "file_ids": (!self.file_ids.is_empty()).then_some(self.file_ids.clone()),
277                "memory_limit": self.memory_limit,
278            })
279        };
280
281        json!({
282            "type": "code_interpreter",
283            "container": container,
284        })
285    }
286}
287
288#[async_trait]
289impl Tool for OpenAICodeInterpreterTool {
290    fn name(&self) -> &str {
291        "openai_code_interpreter"
292    }
293
294    fn description(&self) -> &str {
295        "Uses OpenAI hosted code interpreter to execute Python and return outputs."
296    }
297
298    fn is_builtin(&self) -> bool {
299        true
300    }
301
302    // Runs or acts outside the agent; never assumed safe to repeat.
303    fn effect(&self) -> ToolEffect {
304        ToolEffect::NonIdempotent
305    }
306
307    fn declaration(&self) -> Value {
308        json!({
309            "name": self.name(),
310            "description": self.description(),
311            "x-adk-openai-tool": self.tool_json(),
312        })
313    }
314
315    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
316        Err(adk_core::AdkError::tool("OpenAI code interpreter is handled by the Responses API"))
317    }
318}
319
320/// OpenAI hosted image generation tool.
321#[derive(Debug, Clone, Default)]
322pub struct OpenAIImageGenerationTool {
323    options: Map<String, Value>,
324}
325
326impl OpenAIImageGenerationTool {
327    /// Create a new `OpenAIImageGenerationTool` with default settings.
328    pub fn new() -> Self {
329        Self::default()
330    }
331
332    /// Set a custom option key-value pair for image generation.
333    pub fn with_option(mut self, key: impl Into<String>, value: Value) -> Self {
334        self.options.insert(key.into(), value);
335        self
336    }
337
338    fn tool_json(&self) -> Value {
339        let mut tool = self.options.clone();
340        tool.insert("type".to_string(), Value::String("image_generation".to_string()));
341        Value::Object(tool)
342    }
343}
344
345#[async_trait]
346impl Tool for OpenAIImageGenerationTool {
347    fn name(&self) -> &str {
348        "openai_image_generation"
349    }
350
351    fn description(&self) -> &str {
352        "Uses OpenAI hosted image generation."
353    }
354
355    fn is_builtin(&self) -> bool {
356        true
357    }
358
359    // Runs or acts outside the agent; never assumed safe to repeat.
360    fn effect(&self) -> ToolEffect {
361        ToolEffect::NonIdempotent
362    }
363
364    fn declaration(&self) -> Value {
365        json!({
366            "name": self.name(),
367            "description": self.description(),
368            "x-adk-openai-tool": self.tool_json(),
369        })
370    }
371
372    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
373        Err(adk_core::AdkError::tool("OpenAI image generation is handled by the Responses API"))
374    }
375}
376
377/// OpenAI computer use environment.
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum OpenAIComputerEnvironment {
380    /// Browser-based environment.
381    Browser,
382    /// macOS environment.
383    Mac,
384    /// Windows environment.
385    Windows,
386    /// Generic Linux environment.
387    Linux,
388    /// Ubuntu environment.
389    Ubuntu,
390}
391
392impl OpenAIComputerEnvironment {
393    fn as_wire(self) -> &'static str {
394        match self {
395            Self::Browser => "browser",
396            Self::Mac => "mac",
397            Self::Windows => "windows",
398            Self::Linux => "linux",
399            Self::Ubuntu => "ubuntu",
400        }
401    }
402}
403
404/// OpenAI computer use tool declaration.
405#[derive(Debug, Clone)]
406pub struct OpenAIComputerUseTool {
407    environment: OpenAIComputerEnvironment,
408    display_width: u32,
409    display_height: u32,
410}
411
412impl OpenAIComputerUseTool {
413    /// Create a new `OpenAIComputerUseTool` with the given environment and display dimensions.
414    pub fn new(
415        environment: OpenAIComputerEnvironment,
416        display_width: u32,
417        display_height: u32,
418    ) -> Self {
419        Self { environment, display_width, display_height }
420    }
421
422    fn tool_json(&self) -> Value {
423        json!({
424            "type": "computer_use_preview",
425            "environment": self.environment.as_wire(),
426            "display_width": self.display_width,
427            "display_height": self.display_height,
428        })
429    }
430}
431
432#[async_trait]
433impl Tool for OpenAIComputerUseTool {
434    fn name(&self) -> &str {
435        "openai_computer_use"
436    }
437
438    fn description(&self) -> &str {
439        "Enables OpenAI computer use tool calls."
440    }
441
442    fn is_builtin(&self) -> bool {
443        true
444    }
445
446    // Runs or acts outside the agent; never assumed safe to repeat.
447    fn effect(&self) -> ToolEffect {
448        ToolEffect::NonIdempotent
449    }
450
451    fn declaration(&self) -> Value {
452        json!({
453            "name": self.name(),
454            "description": self.description(),
455            "x-adk-openai-tool": self.tool_json(),
456        })
457    }
458
459    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
460        Err(adk_core::AdkError::tool("OpenAI computer use requires client-side action handling"))
461    }
462}
463
464/// OpenAI remote MCP tool declaration.
465#[derive(Debug, Clone)]
466pub struct OpenAIMcpTool {
467    server_label: String,
468    definition: Map<String, Value>,
469}
470
471impl OpenAIMcpTool {
472    /// Create a new `OpenAIMcpTool` connecting to a server by URL.
473    pub fn new_with_url(server_label: impl Into<String>, server_url: impl Into<String>) -> Self {
474        let server_label = server_label.into();
475        let mut definition = Map::new();
476        definition.insert("type".to_string(), Value::String("mcp".to_string()));
477        definition.insert("server_label".to_string(), Value::String(server_label.clone()));
478        definition.insert("server_url".to_string(), Value::String(server_url.into()));
479        Self { server_label, definition }
480    }
481
482    /// Create a new `OpenAIMcpTool` connecting to a server by connector ID.
483    pub fn new_with_connector(
484        server_label: impl Into<String>,
485        connector_id: impl Into<String>,
486    ) -> Self {
487        let server_label = server_label.into();
488        let mut definition = Map::new();
489        definition.insert("type".to_string(), Value::String("mcp".to_string()));
490        definition.insert("server_label".to_string(), Value::String(server_label.clone()));
491        definition.insert("connector_id".to_string(), Value::String(connector_id.into()));
492        Self { server_label, definition }
493    }
494
495    /// Restrict which tools the model may invoke on this MCP server.
496    pub fn with_allowed_tools(mut self, allowed_tools: Value) -> Self {
497        self.definition.insert("allowed_tools".to_string(), allowed_tools);
498        self
499    }
500
501    /// Set the authorization header value for the MCP server.
502    pub fn with_authorization(mut self, authorization: impl Into<String>) -> Self {
503        self.definition.insert("authorization".to_string(), Value::String(authorization.into()));
504        self
505    }
506
507    /// Set custom headers for the MCP server connection.
508    pub fn with_headers(mut self, headers: Map<String, Value>) -> Self {
509        self.definition.insert("headers".to_string(), Value::Object(headers));
510        self
511    }
512
513    /// Configure tool approval requirements for this MCP server.
514    pub fn with_require_approval(mut self, require_approval: Value) -> Self {
515        self.definition.insert("require_approval".to_string(), require_approval);
516        self
517    }
518
519    fn tool_json(&self) -> Value {
520        Value::Object(self.definition.clone())
521    }
522}
523
524#[async_trait]
525impl Tool for OpenAIMcpTool {
526    fn name(&self) -> &str {
527        &self.server_label
528    }
529
530    fn description(&self) -> &str {
531        "Grants the model access to a remote MCP server."
532    }
533
534    fn is_builtin(&self) -> bool {
535        true
536    }
537
538    // Runs or acts outside the agent; never assumed safe to repeat.
539    fn effect(&self) -> ToolEffect {
540        ToolEffect::NonIdempotent
541    }
542
543    fn declaration(&self) -> Value {
544        json!({
545            "name": self.name(),
546            "description": self.description(),
547            "x-adk-openai-tool": self.tool_json(),
548        })
549    }
550
551    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
552        Err(adk_core::AdkError::tool("OpenAI MCP tool calls are handled by the Responses API"))
553    }
554}
555
556/// OpenAI local shell tool declaration.
557#[derive(Debug, Clone, Default)]
558pub struct OpenAILocalShellTool;
559
560impl OpenAILocalShellTool {
561    /// Create a new `OpenAILocalShellTool`.
562    pub fn new() -> Self {
563        Self
564    }
565}
566
567#[async_trait]
568impl Tool for OpenAILocalShellTool {
569    fn name(&self) -> &str {
570        "openai_local_shell"
571    }
572
573    fn description(&self) -> &str {
574        "Allows OpenAI to execute commands in the local shell tool protocol."
575    }
576
577    fn is_builtin(&self) -> bool {
578        true
579    }
580
581    // Runs or acts outside the agent; never assumed safe to repeat.
582    fn effect(&self) -> ToolEffect {
583        ToolEffect::NonIdempotent
584    }
585
586    fn declaration(&self) -> Value {
587        json!({
588            "name": self.name(),
589            "description": self.description(),
590            "x-adk-openai-tool": {
591                "type": "local_shell"
592            },
593        })
594    }
595
596    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
597        Err(adk_core::AdkError::tool(
598            "OpenAI local shell outputs must be handled through the Responses API item protocol",
599        ))
600    }
601}
602
603/// OpenAI managed shell tool declaration.
604#[derive(Debug, Clone, Default)]
605pub struct OpenAIShellTool {
606    environment: Option<Value>,
607}
608
609impl OpenAIShellTool {
610    /// Create a new `OpenAIShellTool` with default settings.
611    pub fn new() -> Self {
612        Self::default()
613    }
614
615    /// Set the shell environment configuration.
616    pub fn with_environment(mut self, environment: Value) -> Self {
617        self.environment = Some(environment);
618        self
619    }
620
621    fn tool_json(&self) -> Value {
622        json!({
623            "type": "shell",
624            "environment": self.environment,
625        })
626    }
627}
628
629#[async_trait]
630impl Tool for OpenAIShellTool {
631    fn name(&self) -> &str {
632        "openai_shell"
633    }
634
635    fn description(&self) -> &str {
636        "Allows OpenAI to execute commands in the managed shell tool protocol."
637    }
638
639    fn is_builtin(&self) -> bool {
640        true
641    }
642
643    // Runs or acts outside the agent; never assumed safe to repeat.
644    fn effect(&self) -> ToolEffect {
645        ToolEffect::NonIdempotent
646    }
647
648    fn declaration(&self) -> Value {
649        json!({
650            "name": self.name(),
651            "description": self.description(),
652            "x-adk-openai-tool": self.tool_json(),
653        })
654    }
655
656    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
657        Err(adk_core::AdkError::tool(
658            "OpenAI shell outputs must be handled through the Responses API item protocol",
659        ))
660    }
661}
662
663/// OpenAI apply_patch tool declaration.
664#[derive(Debug, Clone, Default)]
665pub struct OpenAIApplyPatchTool;
666
667impl OpenAIApplyPatchTool {
668    /// Create a new `OpenAIApplyPatchTool`.
669    pub fn new() -> Self {
670        Self
671    }
672}
673
674#[async_trait]
675impl Tool for OpenAIApplyPatchTool {
676    fn name(&self) -> &str {
677        "openai_apply_patch"
678    }
679
680    fn description(&self) -> &str {
681        "Allows OpenAI to propose file patches through the native apply_patch tool."
682    }
683
684    fn is_builtin(&self) -> bool {
685        true
686    }
687
688    // Runs or acts outside the agent; never assumed safe to repeat.
689    fn effect(&self) -> ToolEffect {
690        ToolEffect::NonIdempotent
691    }
692
693    fn declaration(&self) -> Value {
694        json!({
695            "name": self.name(),
696            "description": self.description(),
697            "x-adk-openai-tool": {
698                "type": "apply_patch"
699            },
700        })
701    }
702
703    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
704        Err(adk_core::AdkError::tool(
705            "OpenAI apply_patch outputs must be handled through the Responses API item protocol",
706        ))
707    }
708}