mirror of
https://github.com/oobabooga/text-generation-webui.git
synced 2026-03-18 03:14:39 +01:00
Add a calculate tool
This commit is contained in:
parent
286ae475f6
commit
1ed56aee85
48
user_data/tools/calculate.py
Normal file
48
user_data/tools/calculate.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import ast
|
||||
import operator
|
||||
|
||||
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 _eval(node):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
||||
return node.value
|
||||
elif isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
|
||||
return OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
|
||||
elif isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
|
||||
return OPERATORS[type(node.op)](_eval(node.operand))
|
||||
raise ValueError(f"Unsupported expression")
|
||||
|
||||
|
||||
tool = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "calculate",
|
||||
"description": "Evaluate a math expression. Supports +, -, *, /, **, %.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"expression": {"type": "string", "description": "The math expression to evaluate (e.g. '2 * (3 + 4)')."},
|
||||
},
|
||||
"required": ["expression"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def execute(arguments):
|
||||
expr = arguments.get("expression", "")
|
||||
try:
|
||||
tree = ast.parse(expr, mode='eval')
|
||||
result = _eval(tree.body)
|
||||
return {"expression": expr, "result": result}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
Loading…
Reference in a new issue