Skip to main content

oxirs_chat/
custom_tools.rs

1//! Custom Tools Framework
2//!
3//! Extensible framework for adding custom tools and functions that the AI can use
4//! to enhance its capabilities. Supports function calling, parameter validation,
5//! and tool chaining.
6
7use anyhow::{anyhow, Result};
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use serde_json::Value as JsonValue;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use tracing::{debug, info, warn};
15
16/// Tool parameter definition
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct ToolParameter {
19    /// Parameter name
20    pub name: String,
21    /// Parameter description
22    pub description: String,
23    /// Parameter type
24    pub param_type: ParameterType,
25    /// Is this parameter required?
26    pub required: bool,
27    /// Default value (if not required)
28    pub default_value: Option<JsonValue>,
29    /// Parameter constraints
30    pub constraints: Option<ParameterConstraints>,
31}
32
33/// Parameter type
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub enum ParameterType {
36    /// String type
37    String,
38    /// Integer type
39    Integer,
40    /// Float type
41    Float,
42    /// Boolean type
43    Boolean,
44    /// Array of values
45    Array,
46    /// Object/map
47    Object,
48    /// Any JSON value
49    Any,
50}
51
52/// Parameter constraints
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ParameterConstraints {
55    /// Minimum value (for numbers)
56    pub min: Option<f64>,
57    /// Maximum value (for numbers)
58    pub max: Option<f64>,
59    /// Allowed values (enum)
60    pub allowed_values: Option<Vec<JsonValue>>,
61    /// Regex pattern (for strings)
62    pub pattern: Option<String>,
63    /// Minimum length (for strings/arrays)
64    pub min_length: Option<usize>,
65    /// Maximum length (for strings/arrays)
66    pub max_length: Option<usize>,
67}
68
69/// Tool execution result
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ToolResult {
72    /// Success flag
73    pub success: bool,
74    /// Result data
75    pub data: JsonValue,
76    /// Error message (if failed)
77    pub error: Option<String>,
78    /// Execution time in milliseconds
79    pub execution_time_ms: u64,
80    /// Metadata
81    pub metadata: HashMap<String, String>,
82}
83
84/// Tool definition
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct ToolDefinition {
87    /// Tool ID
88    pub id: String,
89    /// Tool name
90    pub name: String,
91    /// Tool description
92    pub description: String,
93    /// Tool parameters
94    pub parameters: Vec<ToolParameter>,
95    /// Tool category
96    pub category: ToolCategory,
97    /// Is tool async?
98    pub is_async: bool,
99    /// Tool tags for discovery
100    pub tags: Vec<String>,
101    /// Examples of usage
102    pub examples: Vec<ToolExample>,
103}
104
105/// Tool category
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107pub enum ToolCategory {
108    /// Data retrieval tools
109    Retrieval,
110    /// Data transformation tools
111    Transformation,
112    /// Analysis tools
113    Analysis,
114    /// External API tools
115    ExternalAPI,
116    /// Utility tools
117    Utility,
118    /// Custom user-defined
119    Custom,
120}
121
122/// Tool usage example
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct ToolExample {
125    /// Example description
126    pub description: String,
127    /// Input parameters
128    pub input: HashMap<String, JsonValue>,
129    /// Expected output
130    pub output: JsonValue,
131}
132
133/// Custom tool trait
134#[async_trait]
135pub trait CustomTool: Send + Sync {
136    /// Get tool definition
137    fn definition(&self) -> ToolDefinition;
138
139    /// Execute the tool
140    async fn execute(&self, parameters: HashMap<String, JsonValue>) -> Result<ToolResult>;
141
142    /// Validate parameters before execution
143    fn validate(&self, parameters: &HashMap<String, JsonValue>) -> Result<()> {
144        let definition = self.definition();
145
146        // Check required parameters
147        for param in &definition.parameters {
148            if param.required && !parameters.contains_key(&param.name) {
149                return Err(anyhow!("Missing required parameter: {}", param.name));
150            }
151
152            // Validate parameter if present
153            if let Some(value) = parameters.get(&param.name) {
154                self.validate_parameter(param, value)?;
155            }
156        }
157
158        Ok(())
159    }
160
161    /// Validate a single parameter
162    fn validate_parameter(&self, param: &ToolParameter, value: &JsonValue) -> Result<()> {
163        // Type validation
164        match param.param_type {
165            ParameterType::String => {
166                if !value.is_string() {
167                    return Err(anyhow!("Parameter {} must be a string", param.name));
168                }
169            }
170            ParameterType::Integer => {
171                if !value.is_i64() && !value.is_u64() {
172                    return Err(anyhow!("Parameter {} must be an integer", param.name));
173                }
174            }
175            ParameterType::Float => {
176                if !value.is_f64() && !value.is_i64() {
177                    return Err(anyhow!("Parameter {} must be a number", param.name));
178                }
179            }
180            ParameterType::Boolean => {
181                if !value.is_boolean() {
182                    return Err(anyhow!("Parameter {} must be a boolean", param.name));
183                }
184            }
185            ParameterType::Array => {
186                if !value.is_array() {
187                    return Err(anyhow!("Parameter {} must be an array", param.name));
188                }
189            }
190            ParameterType::Object => {
191                if !value.is_object() {
192                    return Err(anyhow!("Parameter {} must be an object", param.name));
193                }
194            }
195            ParameterType::Any => {} // Any type is always valid
196        }
197
198        // Constraint validation
199        if let Some(constraints) = &param.constraints {
200            self.validate_constraints(param, value, constraints)?;
201        }
202
203        Ok(())
204    }
205
206    /// Validate parameter constraints
207    fn validate_constraints(
208        &self,
209        param: &ToolParameter,
210        value: &JsonValue,
211        constraints: &ParameterConstraints,
212    ) -> Result<()> {
213        // Numeric constraints
214        if let Some(num) = value.as_f64() {
215            if let Some(min) = constraints.min {
216                if num < min {
217                    return Err(anyhow!("Parameter {} must be >= {}", param.name, min));
218                }
219            }
220            if let Some(max) = constraints.max {
221                if num > max {
222                    return Err(anyhow!("Parameter {} must be <= {}", param.name, max));
223                }
224            }
225        }
226
227        // String/Array length constraints
228        let len = value
229            .as_str()
230            .map(|s| s.len())
231            .or_else(|| value.as_array().map(|arr| arr.len()));
232
233        if let Some(length) = len {
234            if let Some(min_len) = constraints.min_length {
235                if length < min_len {
236                    return Err(anyhow!(
237                        "Parameter {} length must be >= {}",
238                        param.name,
239                        min_len
240                    ));
241                }
242            }
243            if let Some(max_len) = constraints.max_length {
244                if length > max_len {
245                    return Err(anyhow!(
246                        "Parameter {} length must be <= {}",
247                        param.name,
248                        max_len
249                    ));
250                }
251            }
252        }
253
254        // Allowed values constraint
255        if let Some(allowed) = &constraints.allowed_values {
256            if !allowed.contains(value) {
257                return Err(anyhow!(
258                    "Parameter {} must be one of: {:?}",
259                    param.name,
260                    allowed
261                ));
262            }
263        }
264
265        // Pattern constraint (for strings)
266        if let Some(pattern) = &constraints.pattern {
267            if let Some(s) = value.as_str() {
268                let regex = regex::Regex::new(pattern)?;
269                if !regex.is_match(s) {
270                    return Err(anyhow!(
271                        "Parameter {} must match pattern: {}",
272                        param.name,
273                        pattern
274                    ));
275                }
276            }
277        }
278
279        Ok(())
280    }
281}
282
283/// Custom tools registry
284pub struct CustomToolsRegistry {
285    /// Registered tools
286    tools: Arc<RwLock<HashMap<String, Arc<dyn CustomTool>>>>,
287    /// Tool execution history
288    execution_history: Arc<RwLock<Vec<ToolExecution>>>,
289}
290
291/// Tool execution record
292#[derive(Debug, Clone)]
293pub struct ToolExecution {
294    pub tool_id: String,
295    pub timestamp: chrono::DateTime<chrono::Utc>,
296    pub parameters: HashMap<String, JsonValue>,
297    pub result: ToolResult,
298}
299
300impl CustomToolsRegistry {
301    /// Create a new tools registry
302    pub fn new() -> Self {
303        info!("Initialized custom tools registry");
304
305        Self {
306            tools: Arc::new(RwLock::new(HashMap::new())),
307            execution_history: Arc::new(RwLock::new(Vec::new())),
308        }
309    }
310
311    /// Register a custom tool
312    pub async fn register_tool(&self, tool: Arc<dyn CustomTool>) -> Result<()> {
313        let definition = tool.definition();
314        info!("Registering custom tool: {}", definition.id);
315
316        let mut tools = self.tools.write().await;
317        if tools.contains_key(&definition.id) {
318            warn!("Tool {} already exists, replacing", definition.id);
319        }
320
321        tools.insert(definition.id.clone(), tool);
322
323        Ok(())
324    }
325
326    /// Get a tool by ID
327    pub async fn get_tool(&self, tool_id: &str) -> Option<Arc<dyn CustomTool>> {
328        let tools = self.tools.read().await;
329        tools.get(tool_id).cloned()
330    }
331
332    /// List all registered tools
333    pub async fn list_tools(&self) -> Vec<ToolDefinition> {
334        let tools = self.tools.read().await;
335        tools.values().map(|t| t.definition()).collect()
336    }
337
338    /// List tools by category
339    pub async fn list_tools_by_category(&self, category: ToolCategory) -> Vec<ToolDefinition> {
340        let tools = self.tools.read().await;
341        tools
342            .values()
343            .map(|t| t.definition())
344            .filter(|d| d.category == category)
345            .collect()
346    }
347
348    /// Search tools by tag
349    pub async fn search_by_tag(&self, tag: &str) -> Vec<ToolDefinition> {
350        let tools = self.tools.read().await;
351        tools
352            .values()
353            .map(|t| t.definition())
354            .filter(|d| d.tags.iter().any(|t| t == tag))
355            .collect()
356    }
357
358    /// Execute a tool
359    pub async fn execute_tool(
360        &self,
361        tool_id: &str,
362        parameters: HashMap<String, JsonValue>,
363    ) -> Result<ToolResult> {
364        debug!(
365            "Executing tool: {} with parameters: {:?}",
366            tool_id, parameters
367        );
368
369        let tool = self
370            .get_tool(tool_id)
371            .await
372            .ok_or_else(|| anyhow!("Tool not found: {}", tool_id))?;
373
374        // Validate parameters
375        tool.validate(&parameters)?;
376
377        // Execute tool
378        let start_time = std::time::Instant::now();
379        let result = tool.execute(parameters.clone()).await?;
380
381        // Record execution
382        let execution = ToolExecution {
383            tool_id: tool_id.to_string(),
384            timestamp: chrono::Utc::now(),
385            parameters,
386            result: result.clone(),
387        };
388
389        let mut history = self.execution_history.write().await;
390        history.push(execution);
391
392        // Keep history limited
393        if history.len() > 1000 {
394            history.drain(0..500);
395        }
396
397        debug!(
398            "Tool execution completed in {}ms",
399            start_time.elapsed().as_millis()
400        );
401
402        Ok(result)
403    }
404
405    /// Unregister a tool
406    pub async fn unregister_tool(&self, tool_id: &str) -> Result<()> {
407        let mut tools = self.tools.write().await;
408
409        if tools.remove(tool_id).is_none() {
410            return Err(anyhow!("Tool not found: {}", tool_id));
411        }
412
413        info!("Unregistered tool: {}", tool_id);
414        Ok(())
415    }
416
417    /// Get execution history for a tool
418    pub async fn get_execution_history(&self, tool_id: &str) -> Vec<ToolExecution> {
419        let history = self.execution_history.read().await;
420        history
421            .iter()
422            .filter(|e| e.tool_id == tool_id)
423            .cloned()
424            .collect()
425    }
426
427    /// Get execution statistics
428    pub async fn get_statistics(&self) -> ToolStatistics {
429        let tools = self.tools.read().await;
430        let history = self.execution_history.read().await;
431
432        let total_tools = tools.len();
433        let total_executions = history.len();
434
435        let mut execution_counts = HashMap::new();
436        let mut success_counts = HashMap::new();
437
438        for execution in history.iter() {
439            *execution_counts
440                .entry(execution.tool_id.clone())
441                .or_insert(0) += 1;
442
443            if execution.result.success {
444                *success_counts.entry(execution.tool_id.clone()).or_insert(0) += 1;
445            }
446        }
447
448        ToolStatistics {
449            total_tools,
450            total_executions,
451            execution_counts,
452            success_counts,
453        }
454    }
455}
456
457impl Default for CustomToolsRegistry {
458    fn default() -> Self {
459        Self::new()
460    }
461}
462
463/// Tool statistics
464#[derive(Debug, Clone, Serialize, Deserialize)]
465pub struct ToolStatistics {
466    /// Total registered tools
467    pub total_tools: usize,
468    /// Total executions
469    pub total_executions: usize,
470    /// Execution counts per tool
471    pub execution_counts: HashMap<String, usize>,
472    /// Success counts per tool
473    pub success_counts: HashMap<String, usize>,
474}
475
476// Example built-in tool: Echo tool
477pub struct EchoTool;
478
479#[async_trait]
480impl CustomTool for EchoTool {
481    fn definition(&self) -> ToolDefinition {
482        ToolDefinition {
483            id: "echo".to_string(),
484            name: "Echo Tool".to_string(),
485            description: "Simple echo tool that returns the input message".to_string(),
486            parameters: vec![ToolParameter {
487                name: "message".to_string(),
488                description: "Message to echo".to_string(),
489                param_type: ParameterType::String,
490                required: true,
491                default_value: None,
492                constraints: None,
493            }],
494            category: ToolCategory::Utility,
495            is_async: false,
496            tags: vec!["utility".to_string(), "test".to_string()],
497            examples: vec![ToolExample {
498                description: "Echo hello world".to_string(),
499                input: {
500                    let mut map = HashMap::new();
501                    map.insert(
502                        "message".to_string(),
503                        JsonValue::String("hello".to_string()),
504                    );
505                    map
506                },
507                output: JsonValue::String("hello".to_string()),
508            }],
509        }
510    }
511
512    async fn execute(&self, parameters: HashMap<String, JsonValue>) -> Result<ToolResult> {
513        let start_time = std::time::Instant::now();
514
515        let message = parameters
516            .get("message")
517            .and_then(|v| v.as_str())
518            .ok_or_else(|| anyhow!("Missing message parameter"))?;
519
520        Ok(ToolResult {
521            success: true,
522            data: JsonValue::String(message.to_string()),
523            error: None,
524            execution_time_ms: start_time.elapsed().as_millis() as u64,
525            metadata: HashMap::new(),
526        })
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    #[tokio::test]
535    async fn test_registry_creation() {
536        let registry = CustomToolsRegistry::new();
537        let tools = registry.list_tools().await;
538        assert_eq!(tools.len(), 0);
539    }
540
541    #[tokio::test]
542    async fn test_register_and_execute_tool() {
543        let registry = CustomToolsRegistry::new();
544        let echo_tool = Arc::new(EchoTool);
545
546        registry
547            .register_tool(echo_tool)
548            .await
549            .expect("should succeed");
550
551        let mut params = HashMap::new();
552        params.insert("message".to_string(), JsonValue::String("test".to_string()));
553
554        let result = registry
555            .execute_tool("echo", params)
556            .await
557            .expect("should succeed");
558
559        assert!(result.success);
560        assert_eq!(result.data, JsonValue::String("test".to_string()));
561    }
562
563    #[tokio::test]
564    async fn test_list_tools() {
565        let registry = CustomToolsRegistry::new();
566        let echo_tool = Arc::new(EchoTool);
567
568        registry
569            .register_tool(echo_tool)
570            .await
571            .expect("should succeed");
572
573        let tools = registry.list_tools().await;
574        assert_eq!(tools.len(), 1);
575        assert_eq!(tools[0].id, "echo");
576    }
577
578    #[tokio::test]
579    async fn test_parameter_validation() {
580        let registry = CustomToolsRegistry::new();
581        let echo_tool = Arc::new(EchoTool);
582
583        registry
584            .register_tool(echo_tool)
585            .await
586            .expect("should succeed");
587
588        // Missing required parameter
589        let params = HashMap::new();
590        let result = registry.execute_tool("echo", params).await;
591        assert!(result.is_err());
592    }
593
594    #[tokio::test]
595    async fn test_statistics() {
596        let registry = CustomToolsRegistry::new();
597        let echo_tool = Arc::new(EchoTool);
598
599        registry
600            .register_tool(echo_tool)
601            .await
602            .expect("should succeed");
603
604        let mut params = HashMap::new();
605        params.insert("message".to_string(), JsonValue::String("test".to_string()));
606
607        // Execute multiple times
608        for _ in 0..5 {
609            let _ = registry.execute_tool("echo", params.clone()).await;
610        }
611
612        let stats = registry.get_statistics().await;
613        assert_eq!(stats.total_tools, 1);
614        assert_eq!(stats.total_executions, 5);
615    }
616}