mojentic/llm/tools/
simple_date_tool.rs1use crate::error::Result;
2use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
3use async_trait::async_trait;
4use chrono::{Local, NaiveDate};
5use serde_json::{json, Value};
6use std::collections::HashMap;
7
8#[derive(Clone)]
27pub struct SimpleDateTool;
28
29impl SimpleDateTool {
30 fn parse_relative_date(&self, relative_date: &str) -> Result<NaiveDate> {
37 let today = Local::now().date_naive();
38 let lower = relative_date.to_lowercase();
39
40 if lower.contains("today") {
42 return Ok(today);
43 }
44
45 if lower.contains("tomorrow") {
46 return Ok(today + chrono::Duration::days(1));
47 }
48
49 if lower.contains("yesterday") {
50 return Ok(today - chrono::Duration::days(1));
51 }
52
53 if let Some(days) = self.extract_days_offset(&lower, "from now") {
55 return Ok(today + chrono::Duration::days(days));
56 }
57
58 if let Some(days) = self.extract_days_offset(&lower, "ago") {
60 return Ok(today - chrono::Duration::days(days));
61 }
62
63 if lower.contains("next week") {
65 return Ok(today + chrono::Duration::weeks(1));
66 }
67
68 if lower.contains("last week") {
70 return Ok(today - chrono::Duration::weeks(1));
71 }
72
73 Ok(today)
75 }
76
77 fn extract_days_offset(&self, text: &str, suffix: &str) -> Option<i64> {
79 if !text.contains(suffix) {
80 return None;
81 }
82
83 let words: Vec<&str> = text.split_whitespace().collect();
85 for (i, word) in words.iter().enumerate() {
86 if word.contains("day") && i > 0 {
87 if let Ok(num) = words[i - 1].parse::<i64>() {
89 return Some(num);
90 }
91 return Some(match words[i - 1] {
93 "one" | "a" => 1,
94 "two" => 2,
95 "three" => 3,
96 "four" => 4,
97 "five" => 5,
98 "six" => 6,
99 "seven" => 7,
100 _ => 1,
101 });
102 }
103 }
104
105 None
106 }
107}
108
109#[async_trait]
110impl LlmTool for SimpleDateTool {
111 async fn run(
112 &self,
113 args: &HashMap<String, Value>,
114 _ctx: &crate::llm::tools::ToolRunCtx,
115 ) -> Result<Value> {
116 let relative_date =
117 args.get("relative_date").and_then(|v| v.as_str()).ok_or_else(|| {
118 crate::error::MojenticError::ToolError(
119 "Missing required argument: relative_date".to_string(),
120 )
121 })?;
122
123 let resolved_date = self.parse_relative_date(relative_date)?;
124 let formatted_date = resolved_date.format("%Y-%m-%d").to_string();
125
126 Ok(json!({
127 "relative_date": relative_date,
128 "resolved_date": formatted_date,
129 "summary": format!("The date '{}' is {}", relative_date, formatted_date)
130 }))
131 }
132
133 fn descriptor(&self) -> ToolDescriptor {
134 ToolDescriptor {
135 r#type: "function".to_string(),
136 function: FunctionDescriptor {
137 name: "resolve_date".to_string(),
138 description: "Resolves relative date expressions to absolute dates. \
139 Takes text like 'tomorrow', 'three days from now', or 'next week' \
140 and returns the absolute date in YYYY-MM-DD format."
141 .to_string(),
142 parameters: json!({
143 "type": "object",
144 "properties": {
145 "relative_date": {
146 "type": "string",
147 "description": "The relative date expression to resolve (e.g., 'tomorrow', '3 days from now', 'next week')"
148 }
149 },
150 "required": ["relative_date"]
151 }),
152 },
153 }
154 }
155
156 fn clone_box(&self) -> Box<dyn LlmTool> {
157 Box::new(self.clone())
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 #[test]
166 fn test_descriptor() {
167 let tool = SimpleDateTool;
168 let desc = tool.descriptor();
169
170 assert_eq!(desc.r#type, "function");
171 assert_eq!(desc.function.name, "resolve_date");
172 assert!(desc.function.description.contains("relative date"));
173 }
174
175 #[tokio::test]
176 async fn test_resolve_today() {
177 let tool = SimpleDateTool;
178 let args = HashMap::from([("relative_date".to_string(), json!("today"))]);
179
180 let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
181 let today = Local::now().date_naive().format("%Y-%m-%d").to_string();
182
183 assert_eq!(result["relative_date"], "today");
184 assert_eq!(result["resolved_date"], today);
185 }
186
187 #[tokio::test]
188 async fn test_resolve_tomorrow() {
189 let tool = SimpleDateTool;
190 let args = HashMap::from([("relative_date".to_string(), json!("tomorrow"))]);
191
192 let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
193 let tomorrow = (Local::now().date_naive() + chrono::Duration::days(1))
194 .format("%Y-%m-%d")
195 .to_string();
196
197 assert_eq!(result["relative_date"], "tomorrow");
198 assert_eq!(result["resolved_date"], tomorrow);
199 }
200
201 #[tokio::test]
202 async fn test_resolve_days_from_now() {
203 let tool = SimpleDateTool;
204 let args = HashMap::from([("relative_date".to_string(), json!("3 days from now"))]);
205
206 let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
207 let expected = (Local::now().date_naive() + chrono::Duration::days(3))
208 .format("%Y-%m-%d")
209 .to_string();
210
211 assert_eq!(result["resolved_date"], expected);
212 }
213
214 #[tokio::test]
215 async fn test_resolve_days_ago() {
216 let tool = SimpleDateTool;
217 let args = HashMap::from([("relative_date".to_string(), json!("2 days ago"))]);
218
219 let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
220 let expected = (Local::now().date_naive() - chrono::Duration::days(2))
221 .format("%Y-%m-%d")
222 .to_string();
223
224 assert_eq!(result["resolved_date"], expected);
225 }
226
227 #[tokio::test]
228 async fn test_missing_argument() {
229 let tool = SimpleDateTool;
230 let args = HashMap::new();
231
232 let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await;
233 assert!(result.is_err());
234 }
235
236 #[test]
237 fn test_extract_days_offset() {
238 let tool = SimpleDateTool;
239
240 assert_eq!(tool.extract_days_offset("3 days from now", "from now"), Some(3));
241 assert_eq!(tool.extract_days_offset("five days from now", "from now"), Some(5));
242 assert_eq!(tool.extract_days_offset("2 days ago", "ago"), Some(2));
243 assert_eq!(tool.extract_days_offset("tomorrow", "from now"), None);
244 }
245}