Spaces:
Runtime error
Runtime error
| # 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)'." | |
| ), | |
| ) | |