Skip to main content

mojentic/llm/tools/
current_datetime_tool.rs

1use crate::error::Result;
2use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
3use async_trait::async_trait;
4use chrono::Local;
5use serde_json::{json, Value};
6use std::collections::HashMap;
7
8/// Tool for getting the current date and time
9///
10/// This tool returns the current datetime with optional formatting.
11/// It's useful when the LLM needs to know the current time or date.
12///
13/// # Examples
14///
15/// ```ignore
16/// use mojentic::llm::tools::current_datetime_tool::CurrentDatetimeTool;
17///
18/// let tool = CurrentDatetimeTool;
19/// let args = HashMap::new();
20///
21/// let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await?;
22/// // result contains current_datetime, timestamp, and timezone
23/// ```
24#[derive(Clone)]
25pub struct CurrentDatetimeTool;
26
27impl CurrentDatetimeTool {
28    /// Creates a new CurrentDatetimeTool instance
29    pub fn new() -> Self {
30        Self
31    }
32}
33
34impl Default for CurrentDatetimeTool {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40#[async_trait]
41impl LlmTool for CurrentDatetimeTool {
42    async fn run(
43        &self,
44        args: &HashMap<String, Value>,
45        _ctx: &crate::llm::tools::ToolRunCtx,
46    ) -> Result<Value> {
47        let format_string = args
48            .get("format_string")
49            .and_then(|v| v.as_str())
50            .unwrap_or("%Y-%m-%d %H:%M:%S");
51
52        let now = Local::now();
53        let formatted_time = now.format(format_string).to_string();
54        let timestamp = now.timestamp();
55        let timezone = format!("{}", now.offset());
56
57        Ok(json!({
58            "current_datetime": formatted_time,
59            "timestamp": timestamp,
60            "timezone": timezone
61        }))
62    }
63
64    fn descriptor(&self) -> ToolDescriptor {
65        ToolDescriptor {
66            r#type: "function".to_string(),
67            function: FunctionDescriptor {
68                name: "get_current_datetime".to_string(),
69                description: "Get the current date and time. Useful when you need to know the current time or date.".to_string(),
70                parameters: json!({
71                    "type": "object",
72                    "properties": {
73                        "format_string": {
74                            "type": "string",
75                            "description": "Format string for the datetime (e.g., '%Y-%m-%d %H:%M:%S', '%A, %B %d, %Y'). Default is ISO format."
76                        }
77                    },
78                    "required": []
79                }),
80            },
81        }
82    }
83
84    fn clone_box(&self) -> Box<dyn LlmTool> {
85        Box::new(self.clone())
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn test_descriptor() {
95        let tool = CurrentDatetimeTool::new();
96        let descriptor = tool.descriptor();
97
98        assert_eq!(descriptor.r#type, "function");
99        assert_eq!(descriptor.function.name, "get_current_datetime");
100        assert!(descriptor.function.description.contains("current date and time"));
101    }
102
103    #[tokio::test]
104    async fn test_run_with_default_format() {
105        let tool = CurrentDatetimeTool::new();
106        let args = HashMap::new();
107
108        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
109
110        assert!(result.is_object());
111        assert!(result.get("current_datetime").is_some());
112        assert!(result.get("timestamp").is_some());
113        assert!(result.get("timezone").is_some());
114
115        // Check format matches default "%Y-%m-%d %H:%M:%S"
116        let datetime_str = result.get("current_datetime").unwrap().as_str().unwrap();
117        let re = regex::Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$").unwrap();
118        assert!(re.is_match(datetime_str));
119    }
120
121    #[tokio::test]
122    async fn test_run_with_custom_format() {
123        let tool = CurrentDatetimeTool::new();
124        let mut args = HashMap::new();
125        args.insert("format_string".to_string(), json!("%Y-%m-%d"));
126
127        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
128
129        let datetime_str = result.get("current_datetime").unwrap().as_str().unwrap();
130        let re = regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
131        assert!(re.is_match(datetime_str));
132    }
133
134    #[tokio::test]
135    async fn test_timestamp_is_reasonable() {
136        let tool = CurrentDatetimeTool::new();
137        let args = HashMap::new();
138
139        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
140        let timestamp = result.get("timestamp").unwrap().as_i64().unwrap();
141
142        // Timestamp should be reasonable (after 2020, before 2030)
143        assert!(timestamp > 1_577_836_800);
144        assert!(timestamp < 1_893_456_000);
145    }
146
147    #[tokio::test]
148    async fn test_timezone_is_present() {
149        let tool = CurrentDatetimeTool::new();
150        let args = HashMap::new();
151
152        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
153        let timezone = result.get("timezone").unwrap().as_str().unwrap();
154
155        assert!(!timezone.is_empty());
156    }
157
158    #[test]
159    fn test_tool_matches() {
160        let tool = CurrentDatetimeTool::new();
161        assert!(tool.matches("get_current_datetime"));
162        assert!(!tool.matches("other_tool"));
163    }
164
165    #[tokio::test]
166    async fn test_format_with_day_name() {
167        let tool = CurrentDatetimeTool::new();
168        let mut args = HashMap::new();
169        args.insert("format_string".to_string(), json!("%A"));
170
171        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
172        let day_name = result.get("current_datetime").unwrap().as_str().unwrap();
173
174        let valid_days = [
175            "Monday",
176            "Tuesday",
177            "Wednesday",
178            "Thursday",
179            "Friday",
180            "Saturday",
181            "Sunday",
182        ];
183        assert!(valid_days.contains(&day_name));
184    }
185
186    #[tokio::test]
187    async fn test_format_with_month_name() {
188        let tool = CurrentDatetimeTool::new();
189        let mut args = HashMap::new();
190        args.insert("format_string".to_string(), json!("%B"));
191
192        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
193        let month_name = result.get("current_datetime").unwrap().as_str().unwrap();
194
195        let valid_months = [
196            "January",
197            "February",
198            "March",
199            "April",
200            "May",
201            "June",
202            "July",
203            "August",
204            "September",
205            "October",
206            "November",
207            "December",
208        ];
209        assert!(valid_months.contains(&month_name));
210    }
211}