api_ollama 0.2.0

Ollama local LLM runtime API client for HTTP communication.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Enhanced function calling with type-safe execution and validation.
//!
//! Provides a framework for defining, validating, and executing tools/functions
//! with automatic JSON schema generation and type-safe parameter handling.
//!
//! # Architecture
//!
//! The enhanced function calling system consists of:
//! - `ToolExecutor` trait : Defines tool execution interface
//! - `ToolRegistry`: Manages tool registration and dispatch
//! - `ToolResult`: Type-safe result type for tool execution
//! - Helper functions for creating `ToolDefinition` with type safety
//!
//! # Example
//!
//! ```rust,ignore
//! use api_ollama::enhanced_function_calling::{ ToolExecutor, ToolRegistry, ToolResult };
//! use api_ollama::ToolDefinition;
//!
//! // Define a tool executor
//! struct WeatherTool;
//!
//! impl ToolExecutor for WeatherTool
//! {
//!   fn name( &self ) -> &str { "get_weather" }
//!
//!   fn description( &self ) -> &str { "Get weather for a location" }
//!
//!   fn execute( &self, params : serde_json::Value ) -> ToolResult
//!   {
//!     // Extract and validate parameters
//!     let location = params[ "location" ].as_str()
//!       .ok_or( "Missing location parameter" )?;
//!
//!     // Execute tool logic
//!     let result = format!( "Weather in {}: Sunny, 72°F", location );
//!     Ok( result )
//!   }
//! }
//!
//! // Register and use
//! let mut registry = ToolRegistry::new();
//! registry.register( Box::new( WeatherTool ) );
//!
//! let definitions = registry.definitions();
//! // Use definitions in ChatRequest...
//! ```
//!
//! # Future : Procedural Macros
//!
//! The full implementation will include a `#[ tool ]` proc-macro for automatic
//! ToolDefinition generation from function signatures. This requires a separate
//! `ollama_macros` crate and will be implemented in a future phase.

#[ cfg( feature = "enhanced_function_calling" ) ]
mod private
{
  use std::collections::HashMap;
  use std::fmt;

  /// Result type for tool execution
  pub type ToolResult = Result< String, String >;

  /// Trait for executable tools with type-safe parameter handling
  pub trait ToolExecutor : Send + Sync
  {
    /// Get the tool name
    fn name( &self ) -> &str;

    /// Get the tool description
    fn description( &self ) -> &str;

    /// Get the JSON schema for tool parameters
    ///
    /// Returns a JSON schema object describing the expected parameters.
    /// Default implementation returns an empty object schema.
    fn parameter_schema( &self ) -> serde_json::Value
    {
      serde_json ::json!
      ({
        "type" : "object",
        "properties" : {},
        "required" : []
      })
    }

    /// Execute the tool with given parameters
    ///
    /// # Arguments
    ///
    /// * `params` - JSON object containing tool parameters
    ///
    /// # Returns
    ///
    /// Returns the tool execution result as a string, or an error message
    ///
    /// # Errors
    ///
    /// Returns an error if parameters are invalid or execution fails
    fn execute( &self, params : serde_json::Value ) -> ToolResult;

    /// Get the full tool definition for use in API requests
    ///
    /// Automatically generates a `ToolDefinition` from the tool metadata.
    fn definition( &self ) -> crate::ToolDefinition
    {
      crate ::ToolDefinition
      {
        name : self.name().to_string(),
        description : self.description().to_string(),
        parameters : self.parameter_schema(),
      }
    }
  }

  /// Registry for managing and executing tools
  ///
  /// The registry allows registering multiple tools, retrieving their definitions
  /// for API requests, and executing them by name.
  pub struct ToolRegistry
  {
    tools : HashMap< String, Box< dyn ToolExecutor > >,
  }

  impl ToolRegistry
  {
    /// Create a new empty tool registry
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        tools : HashMap::new(),
      }
    }

    /// Register a tool in the registry
    ///
    /// # Arguments
    ///
    /// * `tool` - The tool executor to register
    ///
    /// # Panics
    ///
    /// Panics if a tool with the same name is already registered
    #[ inline ]
    pub fn register( &mut self, tool : Box< dyn ToolExecutor > )
    {
      let name = tool.name().to_string();
      assert!( !self.tools.contains_key( &name ), "Tool '{}' is already registered", name );
      self.tools.insert( name, tool );
    }

    /// Get all tool definitions for use in API requests
    ///
    /// Returns a vector of `ToolDefinition` objects that can be passed
    /// to `ChatRequest::tools`.
    #[ inline ]
    #[ must_use ]
    pub fn definitions( &self ) -> Vec< crate::ToolDefinition >
    {
      self.tools.values()
        .map( | tool | tool.definition() )
        .collect()
    }

    /// Execute a tool by name with given parameters
    ///
    /// # Arguments
    ///
    /// * `tool_call` - The tool call containing name and parameters
    ///
    /// # Returns
    ///
    /// Returns the tool execution result or an error
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Tool is not found in registry
    /// - Tool execution fails
    #[ inline ]
    pub fn execute( &self, tool_call : &crate::ToolCall ) -> ToolResult
    {
      // Extract function name from the tool call
      let function_name = tool_call.function
        .get( "name" )
        .and_then( | v | v.as_str() )
        .ok_or_else( || "Missing function name in tool call".to_string() )?;

      // Get the tool executor
      let tool = self.tools.get( function_name )
        .ok_or_else( || format!( "Tool '{}' not found in registry", function_name ) )?;

      // Extract parameters
      let params = tool_call.function
        .get( "arguments" )
        .cloned()
        .unwrap_or( serde_json::json!( {} ) );

      // Execute the tool
      tool.execute( params )
    }

    /// Get the number of registered tools
    #[ inline ]
    #[ must_use ]
    pub fn len( &self ) -> usize
    {
      self.tools.len()
    }

    /// Check if registry is empty
    #[ inline ]
    #[ must_use ]
    pub fn is_empty( &self ) -> bool
    {
      self.tools.is_empty()
    }

    /// Check if a tool is registered
    #[ inline ]
    #[ must_use ]
    pub fn contains( &self, name : &str ) -> bool
    {
      self.tools.contains_key( name )
    }
  }

  impl Default for ToolRegistry
  {
    #[ inline ]
    fn default() -> Self
    {
      Self::new()
    }
  }

  impl fmt::Debug for ToolRegistry
  {
    fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
    {
      f.debug_struct( "ToolRegistry" )
        .field( "tool_count", &self.tools.len() )
        .field( "tool_names", &self.tools.keys().collect::< Vec< _ > >() )
        .finish()
    }
  }

  /// Helper functions for creating tool definitions with type safety
  pub mod helpers
  {
    use serde_json::json;

    /// Create a simple tool definition with basic parameters
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let tool = create_simple_tool(
    ///   "get_weather",
    ///   "Get weather for a location",
    ///   &[ ( "location", "string", "The city name" ) ],
    ///   &[ "location" ]
    /// );
    /// ```
    #[ inline ]
    #[ must_use ]
    pub fn create_simple_tool(
      name : &str,
      description : &str,
      parameters : &[ ( &str, &str, &str ) ], // (name, type, description)
      required : &[ &str ],
    ) -> crate::ToolDefinition
    {
      let mut properties = serde_json::Map::new();

      for ( param_name, param_type, param_desc ) in parameters
      {
        properties.insert(
          ( *param_name ).to_string(),
          json!
          ({
            "type" : param_type,
            "description" : param_desc,
          })
        );
      }

      crate ::ToolDefinition
      {
        name : name.to_string(),
        description : description.to_string(),
        parameters : json!
        ({
          "type" : "object",
          "properties" : properties,
          "required" : required,
        }),
      }
    }

    /// Create a tool definition with enum parameters
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let tool = create_enum_tool(
    ///   "set_mode",
    ///   "Set operation mode",
    ///   &[ ( "mode", &[ "fast", "slow", "medium" ], "The operation mode" ) ],
    ///   &[ "mode" ]
    /// );
    /// ```
    #[ inline ]
    #[ must_use ]
    pub fn create_enum_tool(
      name : &str,
      description : &str,
      parameters : &[ ( &str, &[ &str ], &str ) ], // (name, enum_values, description)
      required : &[ &str ],
    ) -> crate::ToolDefinition
    {
      let mut properties = serde_json::Map::new();

      for ( param_name, enum_values, param_desc ) in parameters
      {
        properties.insert(
          ( *param_name ).to_string(),
          json!
          ({
            "type" : "string",
            "enum" : enum_values,
            "description" : param_desc,
          })
        );
      }

      crate ::ToolDefinition
      {
        name : name.to_string(),
        description : description.to_string(),
        parameters : json!
        ({
          "type" : "object",
          "properties" : properties,
          "required" : required,
        }),
      }
    }
  }

  /// Orchestration helpers for managing tool execution workflows
  pub mod orchestration
  {
    /// Extract tool calls from a chat response message
    ///
    /// # Returns
    ///
    /// Returns tool calls if present
    #[ cfg( all( feature = "vision_support", feature = "tool_calling" ) ) ]
    #[ inline ]
    pub fn extract_tool_calls( message : &crate::ChatMessage ) -> Option< &Vec< crate::ToolCall > >
    {
      message.tool_calls.as_ref()
    }

    /// Execute multiple tools in sequence using a registry
    ///
    /// Returns vector of results (success or error messages)
    #[ cfg( feature = "tool_calling" ) ]
    #[ inline ]
    pub fn execute_tools_sequential(
      registry : &crate::enhanced_function_calling::ToolRegistry,
      tool_calls : &[ crate::ToolCall ]
    ) -> Vec< String >
    {
      tool_calls
        .iter()
        .map( | call |
        {
          match registry.execute( call )
          {
            Ok( result ) => result,
            Err( e ) => format!( "Error : {}", e ),
          }
        })
        .collect()
    }

    /// Format tool results into tool messages for chat continuation
    ///
    /// # Returns
    ///
    /// Vector of tool messages ready to be added to chat history
    #[ cfg( all( feature = "vision_support", feature = "tool_calling" ) ) ]
    #[ inline ]
    pub fn format_tool_results(
      tool_calls : &[ crate::ToolCall ],
      results : Vec< String >
    ) -> Vec< crate::ToolMessage >
    {
      tool_calls
        .iter()
        .zip( results )
        .map( | ( call, result ) |
        {
          crate::ToolMessage
          {
            role : crate::MessageRole::Tool,
            content : result,
            tool_call_id : call.id.clone(),
          }
        })
        .collect()
    }

    /// Complete orchestration: extract, execute, format
    ///
    /// Helper that combines extraction, execution, and formatting in one call
    ///
    /// Returns tool messages if any tool calls were present, otherwise returns empty vector
    #[ cfg( all( feature = "vision_support", feature = "tool_calling" ) ) ]
    #[ inline ]
    pub fn orchestrate_tool_calls(
      registry : &crate::enhanced_function_calling::ToolRegistry,
      response_message : &crate::ChatMessage
    ) -> Vec< crate::ToolMessage >
    {
      if let Some( tool_calls ) = extract_tool_calls( response_message )
      {
        let results = execute_tools_sequential( registry, tool_calls );
        format_tool_results( tool_calls, results )
      }
      else
      {
        Vec::new()
      }
    }
  }
}

#[ cfg( feature = "enhanced_function_calling" ) ]
crate ::mod_interface!
{
  exposed use private::ToolExecutor;
  exposed use private::ToolRegistry;
  exposed use private::ToolResult;
  exposed use private::helpers;
  exposed use private::orchestration;
}