Example: Adding a Calculator to Our Agent › Step 6: Handle Errors Gracefully

Michael BrenndoerferJune 29, 20251 min read
AI Agent HandbookAll chapters
Part 5 of 15Tool Use - Extending the Agent's Abilities
Chapter 14Example: Adding a Calculator to Our Agent › Step 6: Handle Errors Gracefully
Reading section 8 of 16 · Step 6: Handle Errors Gracefully · 1 minSection 8 of 16 · 1 min

Book contents

Section 8 of 16 · 1 min read

Example: Adding a Calculator to Our Agent › Step 6: Handle Errors GracefullyOne section · Sections in this chapter8 / 16 ↓

What happens when something goes wrong? Let's test error handling:

In[9]:
Code
## Test 6: Invalid expression
print("Test 6: Invalid expression")
print(run_agent_with_calculator("What's the square root of -1?"))
Out[9]:
Console
Test 6: Invalid expression
The square root of -1 is **i** (the imaginary unit).

In mathematics, we can't take the square root of a negative number within the real number system, so mathematicians defined the imaginary unit **i** where:

**i² = -1**

Therefore: **√(-1) = i**

This concept forms the basis of complex numbers, which are written in the form a + bi, where a and b are real numbers. Complex numbers are extremely useful in many areas of mathematics, physics, and engineering.
Test 6: Invalid expression
Agent is using tool: calculate
Tool input: {'expression': '(-1) ** 0.5'}
Tool result: {'success': True, 'result': (6.123233995736766e-17+1j), 'expression': '(-1) ** 0.5'}
The square root of -1 is i (the imaginary unit), which in Python's complex number representation is approximately 1j.

The agent handled this well. Python's eval() returns a complex number for the square root of −1-1, and the agent explained the result in terms the user can understand.

Let's try a truly invalid expression:

In[10]:
Code
## Test 7: Syntax error
print("Test 7: Syntax error")
print(run_agent_with_calculator("Calculate 5 + + 3"))
Out[10]:
Console
Test 7: Syntax error
Agent is using tool: calculate
Tool input: {'expression': '5 + 3'}
Tool result: {'success': True, 'result': 8, 'expression': '5 + 3'}
The answer is **8**.

If you meant something different, please let me know and I'll recalculate!
Test 7: Syntax error
Agent is using tool: calculate
Tool input: {'expression': '5 + + 3'}
Tool result: {'success': False, 'error': 'invalid syntax (<string>, line 1)', 'expression': '5 + + 3'}
I apologize, but there's a syntax error in that expression. The correct way to write it would be "5 + 3", which equals 8.

Perfect. The calculator returned an error, and the agent explained the problem and provided the correct answer.