Skip to main content

api_openai/components/tools/
mod.rs

1//! This module defines various tool-related structures used across the `OpenAI` API.
2
3mod private
4{
5  use serde::{ Deserialize, Serialize };
6  use former::Former;
7  use crate::components::common::Coordinate;
8  use crate::components::output::{ ComputerScreenshotImage, FileSearchResultItem };
9
10  // ============================================================================
11  // Common structures
12  // ============================================================================
13
14  /// Represents the available tools that can be used by models or assistants.
15  ///
16  /// # Used By
17  /// - `CreateChatCompletionRequest`
18  /// - `CreateResponseRequest`
19  /// - `AssistantObject`
20  /// - `RunObject`
21  /// - `CreateRunRequest`
22  /// - `CreateThreadAndRunRequest`
23  /// - `MessageAttachment`
24  /// - `FineTuneChatRequestInput`
25  /// - `FineTunePreferenceInputData`
26  /// - `RealtimeSession`
27  /// - `RealtimeResponseCreateParams`
28  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
29  #[ serde( tag = "type" ) ]
30  #[ non_exhaustive ]
31  pub enum Tool
32  {
33    /// A tool for controlling a virtual computer environment.
34    #[ serde( rename = "computer_use_preview" ) ]
35    ComputerUse( ComputerTool ),
36    /// A tool for searching attached files.
37    #[ serde( rename = "file_search" ) ]
38    FileSearch( FileSearchTool ),
39    /// A custom function defined by the user.
40    #[ serde( rename = "function" ) ]
41    Function( FunctionTool ),
42    /// A tool for searching the web.
43    #[ serde( rename = "web_search_preview" ) ]
44    WebSearch( WebSearchTool ),
45  }
46
47  /// Represents the choice of which tool the model should use.
48  ///
49  /// # Used By
50  /// - `CreateChatCompletionRequest`
51  /// - `CreateResponseRequest`
52  /// - `ResponseProperties` (within `common.rs`)
53  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
54  #[ serde( untagged ) ]
55  #[ non_exhaustive ]
56  pub enum ToolChoice
57  {
58    /// Specifies a specific function to call.
59    Function
60    {
61      /// The function details.
62      function : ToolChoiceFunction,
63      /// The type, always "function".
64      r#type : String,
65    },
66    /// A string indicating the mode ("none", "auto", "required").
67    String( String ),
68  }
69
70  /// Specifies a function name for the `ToolChoice::Function` variant.
71  ///
72  /// # Used By
73  /// - `ToolChoice::Function`
74  /// - `AssistantsNamedToolChoice` (within `assistants_shared.rs`)
75  /// - `ChatCompletionNamedToolChoice` (within `chat_shared.rs`)
76  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
77  #[ non_exhaustive ]
78  pub struct ToolChoiceFunction
79  {
80    /// The name of the function to call.
81    pub name : String,
82  }
83
84  // ============================================================================
85  // Computer Use tool structures
86  // ============================================================================
87
88  /// Defines the computer use tool.
89  /// A tool that controls a virtual computer. Learn more about the [computer tool](/docs/guides/tools-computer-use).
90  ///
91  /// # Used By
92  /// - `Tool::ComputerUse` (within `tools.rs`)
93  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former ) ] // Added Serialize, Former
94  #[ non_exhaustive ]
95  pub struct ComputerTool
96  {
97    // Type is implicitly "computer_use_preview" via parent enum tag
98    /// The height of the computer display.
99    pub display_height : f64,
100    /// The width of the computer display.
101    pub display_width : f64,
102    /// The type of computer environment to control (`mac`, `windows`, `ubuntu`, `browser`).
103    pub environment : String,
104  }
105
106  /// Represents different actions the computer use tool can perform.
107  ///
108  /// # Used By
109  /// - `ComputerToolCall`
110  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
111  #[ serde( tag = "type" ) ]
112  #[ non_exhaustive ]
113  pub enum ComputerAction
114  {
115    /// A click action.
116    #[ serde( rename = "click" ) ]
117    Click
118    {
119      /// Which mouse button was pressed (`left`, `right`, `wheel`, `back`, `forward`).
120      button : String,
121      /// The x-coordinate where the click occurred.
122      x : i64,
123      /// The y-coordinate where the click occurred.
124      y : i64,
125    },
126    /// A double click action.
127    #[ serde( rename = "double_click" ) ]
128    DoubleClick
129    {
130      /// The x-coordinate where the double click occurred.
131      x : i64,
132      /// The y-coordinate where the double click occurred.
133      y : i64,
134    },
135    /// A drag action.
136    #[ serde( rename = "drag" ) ]
137    Drag
138    {
139      /// An array of coordinates representing the path of the drag action.
140      path : Vec< Coordinate >,
141    },
142    /// A collection of keypresses the model would like to perform.
143    #[ serde( rename = "keypress" ) ]
144    KeyPress
145    {
146      /// The combination of keys the model is requesting to be pressed.
147      keys : Vec< String >,
148    },
149    /// A mouse move action.
150    #[ serde( rename = "move" ) ]
151    Move
152    {
153      /// The x-coordinate to move to.
154      x : i64,
155      /// The y-coordinate to move to.
156      y : i64,
157    },
158    /// A screenshot action.
159    #[ serde( rename = "screenshot" ) ]
160    Screenshot {},
161    /// A scroll action.
162    #[ serde( rename = "scroll" ) ]
163    Scroll
164    {
165      /// The x-coordinate where the scroll occurred.
166      x : i64,
167      /// The y-coordinate where the scroll occurred.
168      y : i64,
169      /// The horizontal scroll distance.
170      scroll_x : i64,
171      /// The vertical scroll distance.
172      scroll_y : i64,
173    },
174    /// An action to type in text.
175    #[ serde( rename = "type" ) ]
176    Type
177    {
178      /// The text to type.
179      text : String,
180    },
181    /// A wait action.
182    #[ serde( rename = "wait" ) ]
183    Wait {},
184  }
185
186  /// Represents a safety check associated with a computer tool call.
187  ///
188  /// # Used By
189  /// - `ComputerToolCall`
190  /// - `ComputerToolCallOutput`
191  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ] // Added Serialize
192  #[ non_exhaustive ]
193  pub struct ComputerToolCallSafetyCheck
194  {
195    /// The type code of the pending safety check.
196    pub code : String,
197    /// The ID of the pending safety check.
198    pub id : String,
199    /// Details about the pending safety check.
200    pub message : String,
201  }
202
203  /// Represents a call to the computer use tool.
204  /// See the [computer use guide](/docs/guides/tools-computer-use) for more information.
205  ///
206  /// # Used By
207  /// - `ResponseOutputItem::ComputerCall` (within `responses.rs`)
208  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ] // Added Serialize
209  #[ non_exhaustive ]
210  pub struct ComputerToolCall
211  {
212    /// The specific action requested (e.g., click, type, scroll).
213    pub action : ComputerAction,
214    /// An identifier used when responding to the tool call with output.
215    pub call_id : String,
216    /// The unique ID of the computer call.
217    pub id : String,
218    /// The pending safety checks for the computer call.
219    #[ serde( default ) ]
220    pub pending_safety_checks : Vec< ComputerToolCallSafetyCheck >,
221    /// The status of the item (`in_progress`, `completed`, `incomplete`). Populated when returned via API.
222    pub status : String,
223  }
224
225  /// Represents the output returned from a computer tool call action.
226  ///
227  /// # Used By
228  /// - `InputItem::ComputerCallOutput` (within `responses.rs`)
229  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
230  #[ non_exhaustive ]
231  pub struct ComputerToolCallOutput
232  {
233    /// The safety checks reported by the API that have been acknowledged by the developer.
234    #[ serde( default ) ]
235    pub acknowledged_safety_checks : Vec< ComputerToolCallSafetyCheck >,
236    /// The ID of the computer tool call that produced the output.
237    pub call_id : String,
238    /// The unique ID of the computer call tool output. Populated when returned via API.
239    #[ serde( skip_serializing_if = "Option::is_none" ) ]
240    pub id : Option< String >,
241    /// The output, typically a screenshot image.
242    pub output : ComputerScreenshotImage,
243    /// The status of the message input (`in_progress`, `completed`, `incomplete`). Populated when returned via API.
244    #[ serde( skip_serializing_if = "Option::is_none" ) ]
245    pub status : Option< String >,
246  }
247
248  // ============================================================================
249  // File Search tool structures
250  // ============================================================================
251
252  /// Represents ranking options for file search results.
253  ///
254  /// # Used By
255  /// - `FileSearchTool`
256  /// - `AssistantFileSearchSettings` (within `assistants_shared.rs`)
257  /// - `RunStepDetailsToolCallsFileSearchRankingOptionsObject` (within `assistants_shared.rs`)
258  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Default, Former ) ]
259  #[ non_exhaustive ]
260  pub struct FileSearchRankingOptions
261  {
262    /// The ranker to use for the file search (`auto` or `default_2024_08_21`). Defaults to `auto`.
263    #[ serde( skip_serializing_if = "Option::is_none" ) ]
264    pub ranker : Option< String >,
265    /// The score threshold for the file search (0 to 1). Defaults to 0.
266    #[ serde( skip_serializing_if = "Option::is_none" ) ]
267    pub score_threshold : Option< f64 >,
268  }
269
270  /// Defines a file search tool.
271  ///
272  /// # Used By
273  /// - `Tool::FileSearch` (within `tools.rs`)
274  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Default ) ] // Removed Former
275  #[ non_exhaustive ]
276  pub struct FileSearchTool; // Removed brackets
277
278  /// Represents a call to the file search tool, including queries and results.
279  ///
280  /// # Used By
281  /// - `ResponseOutputItem::FileSearchCall` (within `output.rs`) // Corrected path
282  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ] // Added Serialize
283  #[ non_exhaustive ]
284  pub struct FileSearchToolCall
285  {
286    /// The unique ID of the file search tool call.
287    pub id : String,
288    /// The queries used to search for files.
289    #[ serde( default ) ]
290    pub queries : Vec< String >,
291    /// The results of the file search tool call. Null if the call failed or is still in progress.
292    #[ serde( skip_serializing_if = "Option::is_none" ) ]
293    pub results : Option< Vec< FileSearchResultItem > >, // Uses the imported type
294    /// The status of the file search tool call (`in_progress`, `searching`, `completed`, `failed`).
295    pub status : String,
296  }
297
298  // ============================================================================
299  // Function Calling tool structures
300  // ============================================================================
301
302  /// Represents the parameters for a function tool, described as a JSON Schema object.
303  /// See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the
304  /// [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for
305  /// documentation about the format. Omitting `parameters` defines a function with an empty parameter list.
306  ///
307  /// # Used By
308  /// - `FunctionTool`
309  /// - `AssistantToolsFunction` (within `assistants_shared.rs`)
310  /// - `ChatCompletionFunctions` (within `chat_shared.rs`)
311  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Default ) ]
312  #[ serde( transparent ) ]
313  #[ non_exhaustive ]
314  pub struct FunctionParameters( pub serde_json::Value );
315
316  impl FunctionParameters
317  {
318    /// Creates a new `FunctionParameters` from a JSON value.
319    #[ must_use ]
320    #[ inline ]
321    pub fn new( value : serde_json::Value ) -> Self
322    {
323      Self( value )
324    }
325  }
326
327  /// Defines a function tool that the model can call.
328  ///
329  /// # Used By
330  /// - `Tool::Function` (within `tools.rs`)
331  /// - `AssistantToolsFunction` (within `assistants_shared.rs`)
332  /// - `ChatCompletionTool` (within `chat_shared.rs`)
333  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former ) ]
334  #[ non_exhaustive ]
335  pub struct FunctionTool
336  {
337    // Type is implicitly "function" via parent enum tag
338    /// An optional description of what the function does, used by the model to choose when and how to call the function.
339    #[ serde( skip_serializing_if = "Option::is_none" ) ]
340    pub description : Option< String >,
341    /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
342    pub name : String,
343    /// The parameters the function accepts, described as a JSON Schema object.
344    pub parameters : FunctionParameters,
345    /// Whether to enable strict schema adherence when generating the function call. Defaults to false.
346    #[ serde( skip_serializing_if = "Option::is_none" ) ]
347    pub strict : Option< bool >,
348  }
349
350  /// Represents a call to a function tool, generated by the model.
351  ///
352  /// # Used By
353  /// - `ResponseOutputItem::FunctionCall` (within `responses.rs`)
354  /// - `RealtimeConversationItem` (within `realtime_shared.rs`)
355  /// - `RunStepToolCall::Function` (within `assistants_shared.rs`)
356  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ] // Added Serialize
357  #[ non_exhaustive ]
358  pub struct FunctionToolCall
359  {
360    /// A JSON string of the arguments to pass to the function.
361    pub arguments : String,
362    /// The unique ID of the function tool call generated by the model.
363    pub call_id : String,
364    /// The unique ID of the function tool call. Populated when returned via API.
365    pub id : String,
366    /// The name of the function to run.
367    pub name : String,
368    /// The status of the item (`in_progress`, `completed`, `incomplete`). Populated when returned via API.
369    pub status : String,
370  }
371
372  /// Represents the output returned from a function tool call, to be sent back to the model.
373  ///
374  /// # Used By
375  /// - `InputItem::FunctionCallOutput` (within `responses.rs`)
376  /// - `RealtimeConversationItem` (within `realtime_shared.rs`)
377  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
378  #[ non_exhaustive ]
379  pub struct FunctionToolCallOutput
380  {
381    /// The unique ID of the function tool call generated by the model that this output corresponds to.
382    pub call_id : String,
383    /// The unique ID of the function tool call output. Populated when returned via API.
384    #[ serde( skip_serializing_if = "Option::is_none" ) ]
385    pub id : Option< String >,
386    /// A JSON string of the output of the function tool call.
387    pub output : String,
388    /// The status of the item (`in_progress`, `completed`, `incomplete`). Populated when returned via API.
389    #[ serde( skip_serializing_if = "Option::is_none" ) ]
390    pub status : Option< String >,
391  }
392
393  // ============================================================================
394  // Web Search tool structures
395  // ============================================================================
396
397  /// Defines a web search tool.
398  /// This tool searches the web for relevant results to use in a response.
399  /// Learn more about the [web search tool](/docs/guides/tools-web-search).
400  ///
401  /// # Used By
402  /// - `Tool::WebSearch` (within `tools.rs`)
403  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former, Default ) ] // Added Former back
404  #[ serde( default ) ] // Use defaults for missing fields
405  #[ non_exhaustive ]
406  pub struct WebSearchTool
407  {
408    /// The amount of context window space to use for search results
409    #[ serde( skip_serializing_if = "Option::is_none" ) ]
410    pub search_context_size : Option< String >,
411    /// User location information for search personalization
412    #[ serde( skip_serializing_if = "Option::is_none" ) ]
413    pub user_location : Option< WebSearchUserLocation >,
414  }
415
416  /// User location information for web search personalization
417  ///
418  /// # Used By
419  /// - `WebSearchTool`
420  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former, Default ) ]
421  #[ serde( default ) ]
422  #[ non_exhaustive ]
423  pub struct WebSearchUserLocation
424  {
425    /// Type of location (e.g., "approximate")
426    #[ serde( skip_serializing_if = "Option::is_none" ) ]
427    pub r#type : Option< String >,
428    /// City name
429    #[ serde( skip_serializing_if = "Option::is_none" ) ]
430    pub city : Option< String >,
431    /// Country code
432    #[ serde( skip_serializing_if = "Option::is_none" ) ]
433    pub country : Option< String >,
434    /// Region/state
435    #[ serde( skip_serializing_if = "Option::is_none" ) ]
436    pub region : Option< String >,
437    /// Timezone
438    #[ serde( skip_serializing_if = "Option::is_none" ) ]
439    pub timezone : Option< String >,
440  }
441
442
443  /// Represents a call to the web search tool.
444  /// The results of a web search tool call. See the
445  /// [web search guide](/docs/guides/tools-web-search) for more information.
446  ///
447  /// # Used By
448  /// - `ResponseOutputItem::WebSearchCall` (within `responses.rs`)
449  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ] // Added Serialize
450  #[ non_exhaustive ]
451  pub struct WebSearchToolCall
452  {
453    /// The unique ID of the web search tool call.
454    pub id : String,
455    /// The status of the web search tool call (`in_progress`, `searching`, `completed`, `failed`).
456    pub status : String,
457    // Note : The actual search results are typically included in the subsequent assistant message annotations, not directly in this call object.
458  }
459
460  /// Represents web search context size options.
461  /// High level guidance for the amount of context window space to use for the search.
462  ///
463  /// # Used By
464  /// - `CreateChatCompletionRequest.web_search_options` (within `requests/chat.rs` - *assuming*)
465  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
466  #[ non_exhaustive ]
467  pub struct WebSearchContextSize
468  {
469    /// The context size setting (`low`, `medium`, or `high`). Defaults to `medium`.
470    pub value : String, // Enum : low, medium, high
471  }
472
473  /// Represents approximate location parameters for the web search.
474  ///
475  /// # Used By
476  /// - `CreateChatCompletionRequest.web_search_options` (within `requests/chat.rs` - *assuming*)
477  /// - `WebSearchTool` (as `user_location` field in some contexts, though not directly in the tool definition schema)
478  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
479  #[ non_exhaustive ]
480  pub struct WebSearchLocation
481  {
482    /// Free text input for the city (e.g., "San Francisco").
483    pub city : Option< String >,
484    /// The two-letter ISO country code (e.g., "US").
485    #[ serde( skip_serializing_if = "Option::is_none" ) ]
486    pub country : Option< String >,
487    /// Free text input for the region (e.g., "California").
488    #[ serde( skip_serializing_if = "Option::is_none" ) ]
489    pub region : Option< String >,
490    /// The IANA timezone (e.g., "`America/Los_Angeles`").
491    #[ serde( skip_serializing_if = "Option::is_none" ) ]
492    pub timezone : Option< String >,
493  }
494}
495
496crate ::mod_interface!
497{
498  // Common tool structures
499  exposed use { Tool, ToolChoice, ToolChoiceFunction };
500
501  // Computer Use tool
502  exposed use
503  {
504    ComputerTool,
505    ComputerAction,
506    ComputerToolCallSafetyCheck,
507    ComputerToolCall,
508    ComputerToolCallOutput,
509  };
510
511  // File Search tool
512  exposed use
513  {
514    FileSearchRankingOptions,
515    FileSearchTool,
516    FileSearchToolCall,
517  };
518
519  // Function Calling tool
520  exposed use
521  {
522    FunctionParameters,
523    FunctionTool,
524    FunctionToolCall,
525    FunctionToolCallOutput,
526  };
527
528  // Web Search tool
529  exposed use
530  {
531    WebSearchTool,
532    WebSearchToolCall,
533    WebSearchContextSize,
534    WebSearchLocation,
535    WebSearchUserLocation,
536  };
537
538  // Re-export types used by tool structures
539  own use crate::components::common::Coordinate;
540  own use crate::components::output::{ ComputerScreenshotImage, FileSearchResultItem };
541}