Menu
CoddyTech

Calculator Agent

Part of the Tools and Agents section of Coddy's AI Engineering journey. Lesson 20 of 22.

challenge icon

Challenge

Medium

Build 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.

  1. Define a tool named calculate with the description Calculate the result of a math expression and one required string property, expression.
  2. Send the request with the tool (model="claude-opus-5-5", max_tokens=500) and run the agent loop for at most 4 rounds of tool calls.
  3. For every tool_use block, print Tool: , the name, a space and the input. Send the result as text with str(). When calculate raises ZeroDivisionError, send the error's message with "is_error": True.
  4. Send all of a round's results in one user message.
  5. At the end, print Agent: and the text of the text block, then Tool 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: 2

A model may work out a sum without the tool. For What is 6 * 7? it prints:

Agent: 6 * 7 = 42
Tool calls: 0

Try 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