Calculator Agent
Part of the Tools and Agents section of Coddy's AI Engineering journey. Lesson 20 of 22.
Challenge
MediumBuild an agent that does arithmetic with a calculator tool. The starter reads the request and gives you calculate(expression), which returns the result or raises ZeroDivisionError.
- Define a tool named
calculatewith the descriptionCalculate the result of a math expressionand one required string property,expression. - Send the request with the tool (
model="claude-opus-5-5",max_tokens=500) and run the agent loop for at most4rounds of tool calls. - For every
tool_useblock, printTool:, the name, a space and the input. Send the result as text withstr(). WhencalculateraisesZeroDivisionError, send the error's message with"is_error": True. - Send all of a round's results in one user message.
- At the end, print
Agent:and the text of the text block, thenTool calls:and how many tool calls ran in total.
For example, for the input Calculate 3 * 4 and calculate 10 - 7 the program prints:
Tool: calculate {'expression': '3 * 4'}
Tool: calculate {'expression': '10 - 7'}
Agent: Here is what I found:
- 12
- 3
Tool calls: 2A model may work out a sum without the tool. For What is 6 * 7? it prints:
Agent: 6 * 7 = 42
Tool calls: 0Try it yourself
import coddy_ai as anthropic # in production: import anthropic
import re
client = anthropic.Anthropic()
def calculate(expression):
"""Works out a sum such as 18 * 4 + 6 with + - * / (no brackets)."""
parts = re.findall(r"\d+(?:\.\d+)?|[-+*/]", expression)
values, signs = [float(parts[0])], []
for sign, number in zip(parts[1::2], parts[2::2]):
number = float(number)
if sign == "*":
values[-1] *= number
elif sign == "/":
if number == 0:
raise ZeroDivisionError("Cannot divide by zero")
values[-1] /= number
else:
signs.append(sign)
values.append(number)
total = values[0]
for sign, number in zip(signs, values[1:]):
total = total + number if sign == "+" else total - number
return int(total) if total == int(total) else round(total, 4)
request = input()
# Write your code below
All lessons in Tools and Agents
Practice on your own: Online Python compiler