Files
X-Agents/agent/app/agent/tools/impl/calculator.py

92 lines
2.4 KiB
Python
Raw Normal View History

"""
计算器工具
"""
import ast
import operator
from typing import Any
# 安全运算符
SAFE_OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.Mod: operator.mod,
ast.USub: operator.neg,
}
def safe_eval_expr(node):
"""安全地求值表达式节点"""
if isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
left = safe_eval_expr(node.left)
right = safe_eval_expr(node.right)
op_type = type(node.op)
if op_type in SAFE_OPERATORS:
return SAFE_OPERATORS[op_type](left, right)
raise ValueError(f"Unsupported operator: {op_type}")
elif isinstance(node, ast.UnaryOp):
operand = safe_eval_expr(node.operand)
op_type = type(node.op)
if op_type in SAFE_OPERATORS:
return SAFE_OPERATORS[op_type](operand)
raise ValueError(f"Unsupported unary operator: {op_type}")
else:
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
def calculate(expression: str) -> dict:
"""
执行数学计算
Args:
expression: 数学表达式 "2 + 2" "sqrt(16)"
Returns:
计算结果
"""
try:
# 预处理:处理常见数学函数
expression = expression.replace("sqrt", "**0.5")
expression = expression.replace("pi", "3.14159265359")
expression = expression.replace("e", "2.71828182846")
# 解析表达式
tree = ast.parse(expression, mode='eval')
result = safe_eval_expr(tree.body)
return {
"success": True,
"expression": expression,
"result": result,
"type": type(result).__name__
}
except Exception as e:
return {
"success": False,
"expression": expression,
"error": str(e)
}
# 工具定义
TOOL_DEFINITION = {
"name": "calculator",
"description": "Perform mathematical calculations. Supports basic arithmetic (+, -, *, /), powers (**), and functions (sqrt).",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Mathematical expression to evaluate, e.g., '2 + 2' or 'sqrt(16) + 5'"
}
},
"required": ["expression"]
}
}