27 lines
1.0 KiB
Python
27 lines
1.0 KiB
Python
|
|
from typing import Dict, Any
|
||
|
|
from langchain_core.tools import BaseTool
|
||
|
|
|
||
|
|
|
||
|
|
class CalculatorTool(BaseTool):
|
||
|
|
"""A simple calculator tool for mathematical operations"""
|
||
|
|
|
||
|
|
name: str = "calculator"
|
||
|
|
description: str = "Perform mathematical calculations. Input should be a mathematical expression like '2 + 2' or '10 * (3 + 5)'"
|
||
|
|
|
||
|
|
def _run(self, expression: str) -> str:
|
||
|
|
"""Evaluate a mathematical expression"""
|
||
|
|
try:
|
||
|
|
# Security: Only allow safe mathematical operations
|
||
|
|
allowed_chars = set("0123456789+-*/(). ")
|
||
|
|
if not all(c in allowed_chars for c in expression):
|
||
|
|
return "Error: Expression contains invalid characters"
|
||
|
|
|
||
|
|
# Evaluate the expression
|
||
|
|
result = eval(expression)
|
||
|
|
return f"Result: {result}"
|
||
|
|
except Exception as e:
|
||
|
|
return f"Error calculating expression: {str(e)}"
|
||
|
|
|
||
|
|
async def _arun(self, expression: str) -> str:
|
||
|
|
"""Async version of the tool"""
|
||
|
|
return self._run(expression)
|