Skip to main content

litellm_rs/core/function_calling/
builtin.rs

1//! Built-in function executors
2
3use super::executor::FunctionExecutor;
4use super::types::FunctionDefinition;
5use crate::utils::error::gateway_error::{GatewayError, Result};
6use serde_json::{Value, json};
7
8/// Weather function executor (example)
9pub struct WeatherFunction;
10
11#[async_trait::async_trait]
12impl FunctionExecutor for WeatherFunction {
13    async fn execute(&self, arguments: Value) -> Result<Value> {
14        let location = arguments
15            .get("location")
16            .and_then(|l| l.as_str())
17            .ok_or_else(|| GatewayError::Validation("Missing location parameter".to_string()))?;
18
19        // Mock weather data
20        let weather_data = json!({
21            "location": location,
22            "temperature": "22°C",
23            "condition": "Sunny",
24            "humidity": "65%",
25            "wind": "10 km/h"
26        });
27
28        Ok(weather_data)
29    }
30
31    fn get_schema(&self) -> FunctionDefinition {
32        FunctionDefinition {
33            name: "get_weather".to_string(),
34            description: Some("Get current weather information for a location".to_string()),
35            parameters: json!({
36                "type": "object",
37                "properties": {
38                    "location": {
39                        "type": "string",
40                        "description": "The city and state, e.g. San Francisco, CA"
41                    }
42                },
43                "required": ["location"]
44            }),
45            strict: Some(false),
46        }
47    }
48
49    fn validate_arguments(&self, arguments: &Value) -> Result<()> {
50        if !arguments.is_object() {
51            return Err(GatewayError::Validation(
52                "Arguments must be an object".to_string(),
53            ));
54        }
55
56        if arguments.get("location").is_none() {
57            return Err(GatewayError::Validation(
58                "Missing required parameter: location".to_string(),
59            ));
60        }
61
62        Ok(())
63    }
64}
65
66/// Calculator function executor (example)
67pub struct CalculatorFunction;
68
69#[async_trait::async_trait]
70impl FunctionExecutor for CalculatorFunction {
71    async fn execute(&self, arguments: Value) -> Result<Value> {
72        let expression = arguments
73            .get("expression")
74            .and_then(|e| e.as_str())
75            .ok_or_else(|| GatewayError::Validation("Missing expression parameter".to_string()))?;
76
77        // Simple calculator (in real implementation, use a proper expression parser)
78        let result = match expression {
79            expr if expr.contains("+") => {
80                let parts: Vec<&str> = expr.split('+').collect();
81                if parts.len() == 2 {
82                    let a: f64 = parts[0]
83                        .trim()
84                        .parse()
85                        .map_err(|_| GatewayError::Validation("Invalid number".to_string()))?;
86                    let b: f64 = parts[1]
87                        .trim()
88                        .parse()
89                        .map_err(|_| GatewayError::Validation("Invalid number".to_string()))?;
90                    a + b
91                } else {
92                    return Err(GatewayError::Validation("Invalid expression".to_string()));
93                }
94            }
95            _ => {
96                return Err(GatewayError::Validation(
97                    "Unsupported operation".to_string(),
98                ));
99            }
100        };
101
102        Ok(json!({
103            "expression": expression,
104            "result": result
105        }))
106    }
107
108    fn get_schema(&self) -> FunctionDefinition {
109        FunctionDefinition {
110            name: "calculate".to_string(),
111            description: Some("Perform basic mathematical calculations".to_string()),
112            parameters: json!({
113                "type": "object",
114                "properties": {
115                    "expression": {
116                        "type": "string",
117                        "description": "Mathematical expression to evaluate (e.g., '2 + 3')"
118                    }
119                },
120                "required": ["expression"]
121            }),
122            strict: Some(false),
123        }
124    }
125}