Files
X-Agents/agent/app/agent/tools/impl/calculator.py
DESKTOP-72TV0V4\caoxiaozhu b2bc9988a9 feat: 重构前后端架构,添加Go后端和Python Agent服务
- 新增 Go 语言后端服务(server/),包含用户认证、Agent管理、数据库连接等API
- 新增 Python Agent 服务(agent/),实现Agent核心逻辑和工具集
- 前端从原生HTML迁移到Vue.js框架(web/src/)
- 添加 Docker Compose 支持(docker-compose.yml)
- 添加项目架构文档(docs/ARCHITECTURE.md)
- 添加环境变量示例(.env.example)和本地启动脚本(start-local.ps1)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:39:42 +08:00

92 lines
2.4 KiB
Python

"""
计算器工具
"""
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"]
}
}