Example: Adding a Calculator to Our Agent › Step 1: Create the Calculator Function
Michael BrenndoerferJune 29, 20252 min read
AI Agent HandbookAll chapters Part 5 of 15Tool Use - Extending the Agent's Abilities
Example: Adding a Calculator to Our Agent › Step 1: Create the Calculator FunctionOne section · Sections in this chapter3 / 16 ↓
Sections in this chapter16
First, we need a Python function that performs calculations. We'll use Python's built-in eval() function to evaluate mathematical expressions:
In[3]:
Codedef calculate(expression: str) -> dict:
"""
Evaluate a mathematical expression and return the result.
Args:
expression: A math expression like "1234 * 5678" or "100 + 50 - 25"
Returns:
Dictionary with 'result' or 'error'
"""
try:
# Evaluate the expression
result = eval(expression)
return {
"success": True,
"result": result,
"expression": expression
}
except Exception as e:
return {
"success": False,
"error": str(e),
"expression": expression
}This function takes a string like "1234 * 5678", evaluates it, and returns the result in a structured format. We include error handling so the agent can provide helpful messages if something goes wrong.
Let's test it:
In[4]:
Code## Test the calculator
print(calculate("1234 * 5678"))
print(calculate("100 + 50 - 25"))
print(calculate("10 / 3"))Out[4]:
Console{'success': True, 'result': 7006652, 'expression': '1234 * 5678'}
{'success': True, 'result': 125, 'expression': '100 + 50 - 25'}
{'success': True, 'result': 3.3333333333333335, 'expression': '10 / 3'}{'success': True, 'result': 7006652, 'expression': '1234 * 5678'}
{'success': True, 'result': 125, 'expression': '100 + 50 - 25'}
{'success': True, 'result': 3.3333333333333335, 'expression': '10 / 3'}Perfect. Our calculator works. Now we need to connect it to the agent.
Security Note
Using eval() on untrusted input is dangerous in production. It can execute arbitrary Python code. For this educational example, it's fine since only the agent (not users directly) calls this function. In production, use a safe math parser like ast.literal_eval() or a dedicated math library.