1
This commit is contained in:
@@ -0,0 +1,21 @@
|
|||||||
|
import ast
|
||||||
|
from typing import Any
|
||||||
|
from langchain_core.tools import tool
|
||||||
|
@tool
|
||||||
|
def calculator(expression: str) -> str:
|
||||||
|
"""安全地计算数学表达式。支持 +, -, *, /, %, ** 和括号。"""
|
||||||
|
try:
|
||||||
|
parsed = ast.parse(expression, mode="eval")
|
||||||
|
allowed_nodes = (
|
||||||
|
ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
|
||||||
|
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod, ast.Pow,
|
||||||
|
ast.USub, ast.UAdd, ast.Load,
|
||||||
|
)
|
||||||
|
for node in ast.walk(parsed):
|
||||||
|
if not isinstance(node, allowed_nodes):
|
||||||
|
return f"错误:表达式 '{expression}' 包含不支持的运算或符号,请只用加减乘除、括号和幂运算。"
|
||||||
|
result = eval(compile(parsed, "<calculator>", "eval"), {"__builtins__": {}}, {})
|
||||||
|
return str(result)
|
||||||
|
except Exception as e:
|
||||||
|
return f"计算出错: {str(e)}"
|
||||||
|
|
||||||
Reference in New Issue
Block a user