2026-02-17 02:31:39 +08:00
|
|
|
from typing import Dict, Any
|
|
|
|
|
from langchain_core.tools import BaseTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CalculatorTool(BaseTool):
|
2026-02-26 13:43:44 +08:00
|
|
|
"""用于数学运算的简单计算器工具"""
|
2026-02-17 02:31:39 +08:00
|
|
|
|
|
|
|
|
name: str = "calculator"
|
|
|
|
|
description: str = "Perform mathematical calculations. Input should be a mathematical expression like '2 + 2' or '10 * (3 + 5)'"
|
|
|
|
|
|
|
|
|
|
def _run(self, expression: str) -> str:
|
2026-02-26 13:43:44 +08:00
|
|
|
"""计算数学表达式"""
|
2026-02-17 02:31:39 +08:00
|
|
|
try:
|
2026-02-26 13:43:44 +08:00
|
|
|
# 安全:仅允许安全的数学运算
|
2026-02-17 02:31:39 +08:00
|
|
|
allowed_chars = set("0123456789+-*/(). ")
|
|
|
|
|
if not all(c in allowed_chars for c in expression):
|
|
|
|
|
return "Error: Expression contains invalid characters"
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
# 计算表达式
|
2026-02-17 02:31:39 +08:00
|
|
|
result = eval(expression)
|
|
|
|
|
return f"Result: {result}"
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return f"Error calculating expression: {str(e)}"
|
|
|
|
|
|
|
|
|
|
async def _arun(self, expression: str) -> str:
|
2026-02-26 13:43:44 +08:00
|
|
|
"""工具的异步版本"""
|
2026-02-17 02:31:39 +08:00
|
|
|
return self._run(expression)
|