Spaces:
Runtime error
Runtime error
File size: 1,360 Bytes
eb8c02f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # A safe calculator tool for the executor agent -- deliberately uses sympy instead
# of Python's eval() so a malicious or malformed expression can't run arbitrary code.
# sympy: a symbolic-math library; sympify() parses a string into a math expression
# and evaluates it, without going through Python's own code execution.
import sympy
from llama_index.core.tools import FunctionTool
# Parses and evaluates a math expression string, returning an error message (not
# raising) on failure so the calling agent can see what went wrong and retry.
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression (arithmetic, algebra, basic calculus) and return the result."""
try:
result = sympy.sympify(expression, evaluate=True)
return str(result)
except (sympy.SympifyError, TypeError, ValueError) as e:
return f"Could not evaluate '{expression}': {e}"
# FunctionTool.from_defaults wraps a plain Python function so a LlamaIndex agent can
# call it: the "description" text is what the agent's LLM reads to decide when to use it.
calculate_tool = FunctionTool.from_defaults(
fn=calculate,
name="calculate",
description=(
"Evaluate a mathematical expression using sympy. "
"Use this instead of doing arithmetic yourself. "
"Example input: '(37 * 4) / 2 + sqrt(16)'."
),
)
|