1use async_trait::async_trait;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10use lc_core::tools::{BaseTool, Tool, ToolError};
11
12#[derive(Debug, Deserialize, JsonSchema)]
14pub struct MathInput {
15 pub operation: String,
17
18 pub value: Option<f64>,
20
21 pub value2: Option<f64>,
23
24 pub base: Option<f64>,
26}
27
28#[derive(Debug, Serialize)]
30pub struct MathOutput {
31 pub result: f64,
33
34 pub operation: String,
36
37 pub details: Option<String>,
39}
40
41pub struct SimpleMathTool;
43
44impl SimpleMathTool {
45 pub fn new() -> Self {
47 Self
48 }
49
50 fn power(&self, base: f64, exponent: f64) -> Result<MathOutput, ToolError> {
51 let result = base.powf(exponent);
52 Ok(MathOutput {
53 result,
54 operation: "power".to_string(),
55 details: Some(format!("{}^{} = {}", base, exponent, result)),
56 })
57 }
58
59 fn sqrt(&self, value: f64) -> Result<MathOutput, ToolError> {
60 if value < 0.0 {
61 return Err(ToolError::InvalidInput(
62 "square root requires a non-negative number".to_string(),
63 ));
64 }
65 let result = value.sqrt();
66 Ok(MathOutput {
67 result,
68 operation: "sqrt".to_string(),
69 details: Some(format!("√{} = {}", value, result)),
70 })
71 }
72
73 fn log(&self, value: f64, base: f64) -> Result<MathOutput, ToolError> {
74 if value <= 0.0 || base <= 0.0 || base == 1.0 {
75 return Err(ToolError::InvalidInput(
76 "logarithm requires positive values and a base other than 1".to_string(),
77 ));
78 }
79 let result = value.log(base);
80 Ok(MathOutput {
81 result,
82 operation: "log".to_string(),
83 details: Some(format!("log_{}({}) = {}", base, value, result)),
84 })
85 }
86
87 fn ln(&self, value: f64) -> Result<MathOutput, ToolError> {
88 if value <= 0.0 {
89 return Err(ToolError::InvalidInput(
90 "natural logarithm requires a positive number".to_string(),
91 ));
92 }
93 let result = value.ln();
94 Ok(MathOutput {
95 result,
96 operation: "ln".to_string(),
97 details: Some(format!("ln({}) = {}", value, result)),
98 })
99 }
100
101 fn sin(&self, value: f64) -> Result<MathOutput, ToolError> {
102 let result = value.sin();
103 Ok(MathOutput {
104 result,
105 operation: "sin".to_string(),
106 details: Some(format!("sin({}弧度) = {}", value, result)),
107 })
108 }
109
110 fn cos(&self, value: f64) -> Result<MathOutput, ToolError> {
111 let result = value.cos();
112 Ok(MathOutput {
113 result,
114 operation: "cos".to_string(),
115 details: Some(format!("cos({}弧度) = {}", value, result)),
116 })
117 }
118
119 fn tan(&self, value: f64) -> Result<MathOutput, ToolError> {
120 let result = value.tan();
121 Ok(MathOutput {
122 result,
123 operation: "tan".to_string(),
124 details: Some(format!("tan({}弧度) = {}", value, result)),
125 })
126 }
127
128 fn abs(&self, value: f64) -> Result<MathOutput, ToolError> {
129 let result = value.abs();
130 Ok(MathOutput {
131 result,
132 operation: "abs".to_string(),
133 details: Some(format!("|{}| = {}", value, result)),
134 })
135 }
136
137 fn factorial(&self, value: f64) -> Result<MathOutput, ToolError> {
138 if value < 0.0 {
139 return Err(ToolError::InvalidInput(
140 "factorial requires a non-negative integer".to_string(),
141 ));
142 }
143 if value.is_nan() {
144 return Err(ToolError::InvalidInput(
145 "factorial requires a valid number, NaN is not allowed".to_string(),
146 ));
147 }
148 if value != value.floor() {
149 return Err(ToolError::InvalidInput(
150 "factorial requires an integer, not a decimal".to_string(),
151 ));
152 }
153 let n = value as u64;
154 if n > 20 {
155 return Err(ToolError::InvalidInput(
156 "factorial value too large, maximum supported is 20".to_string(),
157 ));
158 }
159 let result = self.compute_factorial(n);
160 Ok(MathOutput {
161 result: result as f64,
162 operation: "factorial".to_string(),
163 details: Some(format!("{}! = {}", n, result)),
164 })
165 }
166
167 fn compute_factorial(&self, n: u64) -> u64 {
168 if n == 0 || n == 1 {
169 1
170 } else {
171 n * self.compute_factorial(n - 1)
172 }
173 }
174
175 fn mod_op(&self, a: f64, b: f64) -> Result<MathOutput, ToolError> {
176 if b == 0.0 {
177 return Err(ToolError::InvalidInput(
178 "modulo divisor must not be zero".to_string(),
179 ));
180 }
181 let result = a % b;
182 Ok(MathOutput {
183 result,
184 operation: "mod".to_string(),
185 details: Some(format!("{} mod {} = {}", a, b, result)),
186 })
187 }
188
189 fn gcd(&self, a: f64, b: f64) -> Result<MathOutput, ToolError> {
190 let a_int = a as i64;
191 let b_int = b as i64;
192
193 if a_int < 0 || b_int < 0 {
194 return Err(ToolError::InvalidInput(
195 "GCD operation requires positive integers".to_string(),
196 ));
197 }
198
199 let result = self.compute_gcd(a_int.abs(), b_int.abs());
200 Ok(MathOutput {
201 result: result as f64,
202 operation: "gcd".to_string(),
203 details: Some(format!("gcd({}, {}) = {}", a_int, b_int, result)),
204 })
205 }
206
207 fn compute_gcd(&self, a: i64, b: i64) -> i64 {
208 if b == 0 {
209 a
210 } else {
211 self.compute_gcd(b, a % b)
212 }
213 }
214
215 fn lcm(&self, a: f64, b: f64) -> Result<MathOutput, ToolError> {
216 let a_int = a as i64;
217 let b_int = b as i64;
218
219 if a_int <= 0 || b_int <= 0 {
220 return Err(ToolError::InvalidInput(
221 "LCM operation requires positive integers".to_string(),
222 ));
223 }
224
225 let gcd = self.compute_gcd(a_int, b_int);
226 let result = (a_int / gcd)
227 .checked_mul(b_int)
228 .ok_or_else(|| ToolError::InvalidInput("LCM result overflows i64 range".to_string()))?;
229 Ok(MathOutput {
230 result: result as f64,
231 operation: "lcm".to_string(),
232 details: Some(format!("lcm({}, {}) = {}", a_int, b_int, result)),
233 })
234 }
235
236 fn pi(&self) -> MathOutput {
237 MathOutput {
238 result: std::f64::consts::PI,
239 operation: "pi".to_string(),
240 details: Some("π ≈ 3.141592653589793".to_string()),
241 }
242 }
243
244 fn e(&self) -> MathOutput {
245 MathOutput {
246 result: std::f64::consts::E,
247 operation: "e".to_string(),
248 details: Some("e ≈ 2.718281828459045".to_string()),
249 }
250 }
251}
252
253impl Default for SimpleMathTool {
254 fn default() -> Self {
255 Self::new()
256 }
257}
258
259#[async_trait]
260impl Tool for SimpleMathTool {
261 type Input = MathInput;
262 type Output = MathOutput;
263
264 async fn invoke(&self, input: Self::Input) -> Result<Self::Output, ToolError> {
265 match input.operation.as_str() {
266 "power" => {
267 let base = input.value.ok_or_else(||
268 ToolError::InvalidInput("power operation requires a value parameter as the base".to_string()))?;
269 let exp = input.value2.ok_or_else(||
270 ToolError::InvalidInput("power operation requires a value2 parameter as the exponent".to_string()))?;
271 self.power(base, exp)
272 }
273 "sqrt" => {
274 let value = input.value.ok_or_else(||
275 ToolError::InvalidInput("sqrt operation requires a value parameter".to_string()))?;
276 self.sqrt(value)
277 }
278 "log" => {
279 let value = input.value.ok_or_else(||
280 ToolError::InvalidInput("log operation requires a value parameter".to_string()))?;
281 let base = input.base.unwrap_or(10.0);
282 self.log(value, base)
283 }
284 "ln" => {
285 let value = input.value.ok_or_else(||
286 ToolError::InvalidInput("ln operation requires a value parameter".to_string()))?;
287 self.ln(value)
288 }
289 "sin" => {
290 let value = input.value.ok_or_else(||
291 ToolError::InvalidInput("sin operation requires a value parameter (radians)".to_string()))?;
292 self.sin(value)
293 }
294 "cos" => {
295 let value = input.value.ok_or_else(||
296 ToolError::InvalidInput("cos operation requires a value parameter (radians)".to_string()))?;
297 self.cos(value)
298 }
299 "tan" => {
300 let value = input.value.ok_or_else(||
301 ToolError::InvalidInput("tan operation requires a value parameter (radians)".to_string()))?;
302 self.tan(value)
303 }
304 "abs" => {
305 let value = input.value.ok_or_else(||
306 ToolError::InvalidInput("abs operation requires a value parameter".to_string()))?;
307 self.abs(value)
308 }
309 "factorial" => {
310 let value = input.value.ok_or_else(||
311 ToolError::InvalidInput("factorial operation requires a value parameter".to_string()))?;
312 self.factorial(value)
313 }
314 "mod" => {
315 let a = input.value.ok_or_else(||
316 ToolError::InvalidInput("mod operation requires a value parameter".to_string()))?;
317 let b = input.value2.ok_or_else(||
318 ToolError::InvalidInput("mod operation requires a value2 parameter".to_string()))?;
319 self.mod_op(a, b)
320 }
321 "gcd" => {
322 let a = input.value.ok_or_else(||
323 ToolError::InvalidInput("gcd operation requires a value parameter".to_string()))?;
324 let b = input.value2.ok_or_else(||
325 ToolError::InvalidInput("gcd operation requires a value2 parameter".to_string()))?;
326 self.gcd(a, b)
327 }
328 "lcm" => {
329 let a = input.value.ok_or_else(||
330 ToolError::InvalidInput("lcm operation requires a value parameter".to_string()))?;
331 let b = input.value2.ok_or_else(||
332 ToolError::InvalidInput("lcm operation requires a value2 parameter".to_string()))?;
333 self.lcm(a, b)
334 }
335 "pi" => Ok(self.pi()),
336 "e" => Ok(self.e()),
337 _ => Err(ToolError::InvalidInput(
338 format!("unsupported operation: {}, use: power, sqrt, log, ln, sin, cos, tan, abs, factorial, mod, gcd, lcm, pi, e", input.operation)
339 )),
340 }
341 }
342}
343
344#[async_trait]
345impl BaseTool for SimpleMathTool {
346 fn name(&self) -> &str {
347 "math"
348 }
349
350 fn description(&self) -> &str {
351 "高级数学工具。支持多种数学运算:
352
353操作类型:
354- power: 幂运算 (value^value2)
355- sqrt: 平方根
356- log: 对数(可指定底数,默认为10)
357- ln: 自然对数
358- sin, cos, tan: 三角函数(参数为弧度)
359- abs: 绝对值
360- factorial: 阶乘(最大支持20)
361- mod: 取模运算
362- gcd: 最大公约数
363- lcm: 最小公倍数
364- pi: 圆周率
365- e: 自然常数
366
367示例:
368- 幂运算: {\"operation\": \"power\", \"value\": 2, \"value2\": 10}
369- 平方根: {\"operation\": \"sqrt\", \"value\": 16}
370- 对数: {\"operation\": \"log\", \"value\": 100, \"base\": 10}
371- 三角函数: {\"operation\": \"sin\", \"value\": 1.5708}
372- GCD: {\"operation\": \"gcd\", \"value\": 12, \"value2\": 18}"
373 }
374
375 async fn run(&self, input: String) -> Result<String, ToolError> {
376 let parsed: MathInput = serde_json::from_str(&input)
377 .map_err(|e| ToolError::InvalidInput(format!("JSON parse failed: {}", e)))?;
378
379 let output = self.invoke(parsed).await?;
380
381 Ok(format!(
382 "结果: {}\n详细信息: {}",
383 output.result,
384 output.details.unwrap_or_default()
385 ))
386 }
387
388 fn args_schema(&self) -> Option<serde_json::Value> {
389 use schemars::schema_for;
390 serde_json::to_value(schema_for!(MathInput)).ok()
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[tokio::test]
399 async fn test_math_power() {
400 let tool = SimpleMathTool::new();
401
402 let input = MathInput {
403 operation: "power".to_string(),
404 value: Some(2.0),
405 value2: Some(10.0),
406 base: None,
407 };
408
409 let result = tool.invoke(input).await.unwrap();
410 assert_eq!(result.result, 1024.0);
411 }
412
413 #[tokio::test]
414 async fn test_math_sqrt() {
415 let tool = SimpleMathTool::new();
416
417 let input = MathInput {
418 operation: "sqrt".to_string(),
419 value: Some(16.0),
420 value2: None,
421 base: None,
422 };
423
424 let result = tool.invoke(input).await.unwrap();
425 assert_eq!(result.result, 4.0);
426 }
427
428 #[tokio::test]
429 async fn test_math_log() {
430 let tool = SimpleMathTool::new();
431
432 let input = MathInput {
433 operation: "log".to_string(),
434 value: Some(100.0),
435 value2: None,
436 base: Some(10.0),
437 };
438
439 let result = tool.invoke(input).await.unwrap();
440 assert_eq!(result.result, 2.0);
441 }
442
443 #[tokio::test]
444 async fn test_math_ln() {
445 let tool = SimpleMathTool::new();
446
447 let input = MathInput {
448 operation: "ln".to_string(),
449 value: Some(std::f64::consts::E),
450 value2: None,
451 base: None,
452 };
453
454 let result = tool.invoke(input).await.unwrap();
455 assert!((result.result - 1.0).abs() < 0.0001);
456 }
457
458 #[tokio::test]
459 async fn test_math_sin() {
460 let tool = SimpleMathTool::new();
461
462 let input = MathInput {
463 operation: "sin".to_string(),
464 value: Some(std::f64::consts::PI / 2.0),
465 value2: None,
466 base: None,
467 };
468
469 let result = tool.invoke(input).await.unwrap();
470 assert!((result.result - 1.0).abs() < 0.0001);
471 }
472
473 #[tokio::test]
474 async fn test_math_factorial() {
475 let tool = SimpleMathTool::new();
476
477 let input = MathInput {
478 operation: "factorial".to_string(),
479 value: Some(5.0),
480 value2: None,
481 base: None,
482 };
483
484 let result = tool.invoke(input).await.unwrap();
485 assert_eq!(result.result, 120.0);
486 }
487
488 #[tokio::test]
489 async fn test_math_gcd() {
490 let tool = SimpleMathTool::new();
491
492 let input = MathInput {
493 operation: "gcd".to_string(),
494 value: Some(12.0),
495 value2: Some(18.0),
496 base: None,
497 };
498
499 let result = tool.invoke(input).await.unwrap();
500 assert_eq!(result.result, 6.0);
501 }
502
503 #[tokio::test]
504 async fn test_math_lcm() {
505 let tool = SimpleMathTool::new();
506
507 let input = MathInput {
508 operation: "lcm".to_string(),
509 value: Some(4.0),
510 value2: Some(6.0),
511 base: None,
512 };
513
514 let result = tool.invoke(input).await.unwrap();
515 assert_eq!(result.result, 12.0);
516 }
517
518 #[tokio::test]
519 async fn test_math_pi() {
520 let tool = SimpleMathTool::new();
521
522 let input = MathInput {
523 operation: "pi".to_string(),
524 value: None,
525 value2: None,
526 base: None,
527 };
528
529 let result = tool.invoke(input).await.unwrap();
530 assert!((result.result - std::f64::consts::PI).abs() < 0.0001);
531 }
532
533 #[tokio::test]
534 async fn test_math_abs() {
535 let tool = SimpleMathTool::new();
536
537 let input = MathInput {
538 operation: "abs".to_string(),
539 value: Some(-5.0),
540 value2: None,
541 base: None,
542 };
543
544 let result = tool.invoke(input).await.unwrap();
545 assert_eq!(result.result, 5.0);
546 }
547
548 #[tokio::test]
549 async fn test_math_sqrt_negative_error() {
550 let tool = SimpleMathTool::new();
551
552 let input = MathInput {
553 operation: "sqrt".to_string(),
554 value: Some(-4.0),
555 value2: None,
556 base: None,
557 };
558
559 let result = tool.invoke(input).await;
560 assert!(result.is_err());
561 }
562
563 #[tokio::test]
564 async fn test_math_factorial_overflow_error() {
565 let tool = SimpleMathTool::new();
566
567 let input = MathInput {
568 operation: "factorial".to_string(),
569 value: Some(25.0),
570 value2: None,
571 base: None,
572 };
573
574 let result = tool.invoke(input).await;
575 assert!(result.is_err());
576 }
577
578 #[tokio::test]
579 async fn test_math_base_tool_run() {
580 let tool = SimpleMathTool::new();
581
582 let input = "{\"operation\": \"power\", \"value\": 3, \"value2\": 4}".to_string();
583 let result = tool.run(input).await.unwrap();
584
585 assert!(result.contains("81"));
586 assert!(result.contains("3^4"));
587 }
588}