Skip to main content

litellm_rs/core/function_calling/
executor.rs

1//! Function executor trait and handler implementation
2
3use super::types::*;
4use crate::utils::error::gateway_error::Result;
5use serde_json::Value;
6use std::collections::HashMap;
7
8/// Trait for executing functions
9#[async_trait::async_trait]
10pub trait FunctionExecutor: Send + Sync {
11    /// Execute the function with given arguments
12    async fn execute(&self, arguments: Value) -> Result<Value>;
13
14    /// Get function schema
15    fn get_schema(&self) -> FunctionDefinition;
16
17    /// Validate function arguments
18    fn validate_arguments(&self, _arguments: &Value) -> Result<()> {
19        // Default implementation - can be overridden
20        Ok(())
21    }
22}
23
24/// Function calling handler
25pub struct FunctionCallingHandler {
26    /// Available functions
27    pub(crate) functions: HashMap<String, FunctionDefinition>,
28    /// Function execution handlers
29    pub(crate) executors: HashMap<String, Box<dyn FunctionExecutor>>,
30}
31
32impl FunctionCallingHandler {
33    /// Create a new function calling handler
34    pub fn new() -> Self {
35        Self {
36            functions: HashMap::new(),
37            executors: HashMap::new(),
38        }
39    }
40
41    /// Register a function
42    pub fn register_function<F>(&mut self, name: String, executor: F) -> Result<()>
43    where
44        F: FunctionExecutor + 'static,
45    {
46        let schema = executor.get_schema();
47        self.functions.insert(name.clone(), schema);
48        self.executors.insert(name, Box::new(executor));
49        Ok(())
50    }
51
52    /// Get available functions as tool definitions
53    pub fn get_tool_definitions(&self) -> Vec<ToolDefinition> {
54        self.functions
55            .values()
56            .map(|function| ToolDefinition {
57                tool_type: "function".to_string(),
58                function: function.clone(),
59            })
60            .collect()
61    }
62}
63
64impl Default for FunctionCallingHandler {
65    fn default() -> Self {
66        Self::new()
67    }
68}