lc-tools 0.19.0

Built-in tools for langchainrust — Calculator, DateTime, URLFetch, etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// lc-tools/src/datetime.rs
//! Date and time tool for agents.
//!
//! Provides date/time query and calculation functionality.

use async_trait::async_trait;
use chrono::{DateTime, Datelike, Duration, Local, NaiveDate, NaiveDateTime, TimeZone, Weekday};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use lc_core::tools::{BaseTool, Tool, ToolError};

/// DateTime tool input parameters.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DateTimeInput {
    /// Operation type: "now", "format", "add", "subtract", "weekday", "diff".
    pub operation: String,

    /// Date/time string (optional, format: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS).
    pub datetime: Option<String>,

    /// Time unit: "days", "hours", "minutes", "weeks", "months", "years".
    pub unit: Option<String>,

    /// Value for add/subtract operations.
    pub value: Option<i64>,

    /// Target date/time for diff operation.
    pub target: Option<String>,
}

/// DateTime tool output result.
#[derive(Debug, Serialize)]
pub struct DateTimeOutput {
    /// Operation result.
    pub result: String,

    /// Operation type.
    pub operation: String,

    /// Additional details.
    pub details: Option<String>,
}

/// DateTime tool for querying and manipulating dates and times.
pub struct DateTimeTool;

impl DateTimeTool {
    /// Creates a new DateTimeTool instance.
    pub fn new() -> Self {
        Self
    }

    fn parse_datetime(&self, dt_str: &str) -> Result<DateTime<Local>, ToolError> {
        if let Ok(dt) = NaiveDateTime::parse_from_str(dt_str, "%Y-%m-%d %H:%M:%S") {
            return Local
                .from_local_datetime(&dt)
                .single()
                .ok_or_else(|| ToolError::ExecutionFailed("invalid datetime".to_string()));
        }

        if let Ok(date) = NaiveDate::parse_from_str(dt_str, "%Y-%m-%d") {
            let dt = date
                .and_hms_opt(0, 0, 0)
                .ok_or_else(|| ToolError::ExecutionFailed("invalid date".to_string()))?;
            return Local
                .from_local_datetime(&dt)
                .single()
                .ok_or_else(|| ToolError::ExecutionFailed("invalid datetime".to_string()));
        }

        Err(ToolError::ExecutionFailed(format!(
            "failed to parse datetime: {}, use format YYYY-MM-DD or YYYY-MM-DD HH:MM:SS",
            dt_str
        )))
    }

    fn get_now(&self) -> DateTimeOutput {
        let now = Local::now();
        DateTimeOutput {
            result: now.format("%Y-%m-%d %H:%M:%S").to_string(),
            operation: "now".to_string(),
            details: Some(format!(
                "星期{},第{}",
                match now.weekday() {
                    Weekday::Mon => "",
                    Weekday::Tue => "",
                    Weekday::Wed => "",
                    Weekday::Thu => "",
                    Weekday::Fri => "",
                    Weekday::Sat => "",
                    Weekday::Sun => "",
                },
                now.iso_week().week()
            )),
        }
    }

    fn format_datetime(&self, dt_str: &str) -> Result<DateTimeOutput, ToolError> {
        let dt = self.parse_datetime(dt_str)?;

        Ok(DateTimeOutput {
            result: dt.format("%Y年%m月%d日 %H时%M分%S秒").to_string(),
            operation: "format".to_string(),
            details: Some(format!(
                "星期{}{}{}",
                match dt.weekday() {
                    Weekday::Mon => "",
                    Weekday::Tue => "",
                    Weekday::Wed => "",
                    Weekday::Thu => "",
                    Weekday::Fri => "",
                    Weekday::Sat => "",
                    Weekday::Sun => "",
                },
                dt.year(),
                dt.iso_week().week()
            )),
        })
    }

    fn add_time(&self, dt_str: &str, value: i64, unit: &str) -> Result<DateTimeOutput, ToolError> {
        let dt = self.parse_datetime(dt_str)?;

        let new_dt = match unit {
            "seconds" => dt + Duration::seconds(value),
            "minutes" => dt + Duration::minutes(value),
            "hours" => dt + Duration::hours(value),
            "days" => dt + Duration::days(value),
            "weeks" => dt + Duration::weeks(value),
            "months" => {
                let months = value as i32;
                let new_month = dt.month() as i32 + months;
                let year = dt.year() + (new_month - 1) / 12;
                let month = ((new_month - 1) % 12 + 1) as u32;

                dt.with_year(year)
                    .and_then(|d| d.with_month(month))
                    .ok_or_else(|| ToolError::ExecutionFailed("month calculation failed".to_string()))?
            }
            "years" => dt
                .with_year(dt.year() + value as i32)
                .ok_or_else(|| ToolError::ExecutionFailed("year calculation failed".to_string()))?,
            _ => {
                return Err(ToolError::ExecutionFailed(format!(
                "unsupported time unit: {}, use: seconds, minutes, hours, days, weeks, months, years",
                unit
            )))
            }
        };

        Ok(DateTimeOutput {
            result: new_dt.format("%Y-%m-%d %H:%M:%S").to_string(),
            operation: "add".to_string(),
            details: Some(format!("{} {}", value, self.unit_to_chinese(unit))),
        })
    }

    fn subtract_time(
        &self,
        dt_str: &str,
        value: i64,
        unit: &str,
    ) -> Result<DateTimeOutput, ToolError> {
        self.add_time(dt_str, -value, unit)
    }

    fn get_weekday(&self, dt_str: &str) -> Result<DateTimeOutput, ToolError> {
        let dt = self.parse_datetime(dt_str)?;

        let weekday = match dt.weekday() {
            Weekday::Mon => "星期一",
            Weekday::Tue => "星期二",
            Weekday::Wed => "星期三",
            Weekday::Thu => "星期四",
            Weekday::Fri => "星期五",
            Weekday::Sat => "星期六",
            Weekday::Sun => "星期日",
        };

        Ok(DateTimeOutput {
            result: weekday.to_string(),
            operation: "weekday".to_string(),
            details: Some(format!("{}{}", dt.format("%Y-%m-%d"), weekday)),
        })
    }

    fn diff_time(&self, dt1_str: &str, dt2_str: &str) -> Result<DateTimeOutput, ToolError> {
        let dt1 = self.parse_datetime(dt1_str)?;
        let dt2 = self.parse_datetime(dt2_str)?;

        let diff = dt2.signed_duration_since(dt1);

        let days = diff.num_days();
        let hours = diff.num_hours() % 24;
        let minutes = diff.num_minutes() % 60;

        Ok(DateTimeOutput {
            result: format!("{}{}小时 {}分钟", days.abs(), hours.abs(), minutes.abs()),
            operation: "diff".to_string(),
            details: Some(if diff.num_seconds() >= 0 {
                format!(
                    "{}{} 相隔 {}{}小时 {}分钟",
                    dt1.format("%Y-%m-%d"),
                    dt2.format("%Y-%m-%d"),
                    days,
                    hours,
                    minutes
                )
            } else {
                format!(
                    "{}{} 相隔 {}{}小时 {}分钟",
                    dt2.format("%Y-%m-%d"),
                    dt1.format("%Y-%m-%d"),
                    days.abs(),
                    hours.abs(),
                    minutes.abs()
                )
            }),
        })
    }

    fn unit_to_chinese(&self, unit: &str) -> String {
        match unit {
            "seconds" => "",
            "minutes" => "分钟",
            "hours" => "小时",
            "days" => "",
            "weeks" => "",
            "months" => "",
            "years" => "",
            _ => unit,
        }
        .to_string()
    }
}

impl Default for DateTimeTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Tool for DateTimeTool {
    type Input = DateTimeInput;
    type Output = DateTimeOutput;

    async fn invoke(&self, input: Self::Input) -> Result<Self::Output, ToolError> {
        match input.operation.as_str() {
            "now" => Ok(self.get_now()),
            "format" => {
                let dt = input.datetime.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "format operation requires a datetime parameter".to_string(),
                    )
                })?;
                self.format_datetime(&dt)
            }
            "add" => {
                let dt = input.datetime.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "add operation requires a datetime parameter".to_string(),
                    )
                })?;
                let value = input.value.ok_or_else(|| {
                    ToolError::InvalidInput("add operation requires a value parameter".to_string())
                })?;
                let unit = input.unit.ok_or_else(|| {
                    ToolError::InvalidInput("add operation requires a unit parameter".to_string())
                })?;
                self.add_time(&dt, value, &unit)
            }
            "subtract" => {
                let dt = input.datetime.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "subtract operation requires a datetime parameter".to_string(),
                    )
                })?;
                let value = input.value.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "subtract operation requires a value parameter".to_string(),
                    )
                })?;
                let unit = input.unit.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "subtract operation requires a unit parameter".to_string(),
                    )
                })?;
                self.subtract_time(&dt, value, &unit)
            }
            "weekday" => {
                let dt = input.datetime.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "weekday operation requires a datetime parameter".to_string(),
                    )
                })?;
                self.get_weekday(&dt)
            }
            "diff" => {
                let dt1 = input.datetime.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "diff operation requires a datetime parameter".to_string(),
                    )
                })?;
                let dt2 = input.target.ok_or_else(|| {
                    ToolError::InvalidInput(
                        "diff operation requires a target parameter".to_string(),
                    )
                })?;
                self.diff_time(&dt1, &dt2)
            }
            _ => Err(ToolError::InvalidInput(format!(
                "unsupported operation: {}, use: now, format, add, subtract, weekday, diff",
                input.operation
            ))),
        }
    }
}

#[async_trait]
impl BaseTool for DateTimeTool {
    fn name(&self) -> &str {
        "datetime"
    }

    fn description(&self) -> &str {
        "日期时间工具。支持多种操作:

操作类型:
- now: 获取当前时间
- format: 格式化日期时间
- add: 添加时间
- subtract: 减去时间
- weekday: 获取星期几
- diff: 计算时间差

示例:
- 获取当前时间: {\"operation\": \"now\"}
- 格式化日期: {\"operation\": \"format\", \"datetime\": \"2024-01-15\"}
- 添加3天: {\"operation\": \"add\", \"datetime\": \"2024-01-15\", \"value\": 3, \"unit\": \"days\"}
- 计算差值: {\"operation\": \"diff\", \"datetime\": \"2024-01-01\", \"target\": \"2024-01-15\"}"
    }

    async fn run(&self, input: String) -> Result<String, ToolError> {
        let parsed: DateTimeInput = serde_json::from_str(&input)
            .map_err(|e| ToolError::InvalidInput(format!("JSON parse failed: {}", e)))?;

        let output = self.invoke(parsed).await?;

        Ok(format!(
            "{}\n详细信息: {}",
            output.result,
            output.details.unwrap_or_default()
        ))
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        use schemars::schema_for;
        serde_json::to_value(schema_for!(DateTimeInput)).ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_datetime_now() {
        let tool = DateTimeTool::new();

        let input = DateTimeInput {
            operation: "now".to_string(),
            datetime: None,
            unit: None,
            value: None,
            target: None,
        };

        let result = tool.invoke(input).await.unwrap();
        assert!(!result.result.is_empty());
        assert!(result.details.is_some());
    }

    #[tokio::test]
    async fn test_datetime_format() {
        let tool = DateTimeTool::new();

        let input = DateTimeInput {
            operation: "format".to_string(),
            datetime: Some("2024-01-15".to_string()),
            unit: None,
            value: None,
            target: None,
        };

        let result = tool.invoke(input).await.unwrap();
        assert!(result.result.contains("2024年"));
        assert!(result.result.contains("01月"));
        assert!(result.result.contains("15日"));
    }

    #[tokio::test]
    async fn test_datetime_add_days() {
        let tool = DateTimeTool::new();

        let input = DateTimeInput {
            operation: "add".to_string(),
            datetime: Some("2024-01-15".to_string()),
            unit: Some("days".to_string()),
            value: Some(3),
            target: None,
        };

        let result = tool.invoke(input).await.unwrap();
        assert!(result.result.contains("2024-01-18"));
    }

    #[tokio::test]
    async fn test_datetime_weekday() {
        let tool = DateTimeTool::new();

        // 2024-01-15 is a Monday
        let input = DateTimeInput {
            operation: "weekday".to_string(),
            datetime: Some("2024-01-15".to_string()),
            unit: None,
            value: None,
            target: None,
        };

        let result = tool.invoke(input).await.unwrap();
        assert_eq!(result.result, "星期一");
    }

    #[tokio::test]
    async fn test_datetime_diff() {
        let tool = DateTimeTool::new();

        let input = DateTimeInput {
            operation: "diff".to_string(),
            datetime: Some("2024-01-01".to_string()),
            unit: None,
            value: None,
            target: Some("2024-01-15".to_string()),
        };

        let result = tool.invoke(input).await.unwrap();
        assert!(result.result.contains("14天"));
    }
}