2
Basic Calculator Agent
BeginnerLearn input validation, error handling, and security best practices by building a safe math calculator.
What You'll Learn
Input Validation
Secure input filtering and validation
Error Handling
Graceful error management and feedback
Multiple Tools
Integrating several tools in one agent
System Prompts
Guide tool selection with prompts
Basic Calculator
1from connectonion import Agent
2
3def calculate(expression: str) -> str:
4 """Safely evaluate basic math expressions."""
5 try:
6 # Only allow safe characters
7 allowed = set('0123456789+-*/()., ')
8 if not all(c in allowed for c in expression):
9 return "Error: Only basic math operations allowed"
10
11 result = eval(expression)
12 return f"{expression} = {result}"
13 except Exception as e:
14 return f"Error: {str(e)}"
15
16def get_help() -> str:
17 """Get help about available math operations."""
18 return """Available operations:
19 + Addition
20 - Subtraction
21 * Multiplication
22 / Division
23 () Parentheses for grouping
24
25 Example: 2 + 3 * 4"""
26
27# Create calculator agent
28agent = Agent(
29 name="calculator",
30 tools=[calculate, get_help]
31)
32
33response = agent.input("What's 25 + 17 * 3?")
34print(response)
Complete Example with Security
1# calculator_agent.py
2import os
3from connectonion import Agent
4
5# Set your OpenAI API key
6os.environ['OPENAI_API_KEY'] = 'your-api-key-here'
7
8def calculate(expression: str) -> str:
9 """Safely evaluate basic math expressions like 2+3*4."""
10 try:
11 # Input validation - only allow safe mathematical characters
12 allowed_chars = set('0123456789+-*/()., ')
13 if not all(c in allowed_chars for c in expression):
14 return "Error: Only basic math operations (+, -, *, /, parentheses) are allowed"
15
16 # Prevent empty expressions
17 if not expression.strip():
18 return "Error: Please provide a math expression"
19
20 # Evaluate the expression safely
21 result = eval(expression)
22 return f"Calculation: {expression} = {result}"
23 except ZeroDivisionError:
24 return f"Error: Division by zero in expression '{expression}'"
25 except Exception as e:
26 return f"Math Error: {str(e)} in expression '{expression}'"
27
28def get_help() -> str:
29 """Get help about available math operations and examples."""
30 return """🧮 Calculator Help
31
32Available operations:
33• Addition: +
34• Subtraction: -
35• Multiplication: *
36• Division: /
37• Parentheses: () for grouping
38• Decimals: . (like 3.14)
39
40Examples:
41• Simple: 2 + 3
42• Complex: (10 + 5) * 2 / 3
43• Decimals: 3.14 * 2.5
44• Order of operations: 2 + 3 * 4 = 14 (not 20!)"""
45
46def validate_expression(expression: str) -> str:
47 """Check if a math expression is valid before calculating."""
48 if not expression or not expression.strip():
49 return "❌ Empty expression - please provide a math problem"
50
51 allowed_chars = set('0123456789+-*/()., ')
52 invalid_chars = [c for c in expression if c not in allowed_chars]
53
54 if invalid_chars:
55 return f"❌ Invalid characters found: {', '.join(set(invalid_chars))}. Only use: 0-9, +, -, *, /, (, ), ."
56
57 # Check for basic syntax issues
58 if expression.count('(') != expression.count(')'):
59 return "❌ Mismatched parentheses"
60
61 return "✅ Expression looks valid!"
62
63# Create the calculator agent
64agent = Agent(
65 name="calculator",
66 system_prompt="""You are a helpful calculator assistant.
67 Always use the calculate() function for math operations.
68 If users ask for help or seem confused, use get_help().
69 If they want to check an expression first, use validate_expression().""",
70 tools=[calculate, get_help, validate_expression]
71)
72
73if __name__ == "__main__":
74 print("=== Calculator Agent Demo ===\n")
75
76 # Test various calculations
77 test_cases = [
78 "What's 25 + 17 * 3?",
79 "Help me understand what operations are available",
80 "Is '2 + 3 *' a valid expression?",
81 "Calculate (100 - 25) / 5 + 10",
82 "What's 22 / 7?"
83 ]
84
85 for i, test in enumerate(test_cases, 1):
86 print(f"Test {i}: {test}")
87 response = agent.input(test)
88 print(f"Response: {response}\n")
89 print("-" * 50)
Expected Output
=== Calculator Agent Demo === Test 1: What's 25 + 17 * 3? Response: Calculation: 25 + 17 * 3 = 76 Test 2: Help me understand what operations are available Response: 🧮 Calculator Help Available operations: • Addition: + • Subtraction: - • Multiplication: * • Division: / • Parentheses: () for grouping • Decimals: . (like 3.14) Test 3: Is '2 + 3 *' a valid expression? Response: ❌ Expression looks invalid - incomplete operation Test 4: Calculate (100 - 25) / 5 + 10 Response: Calculation: (100 - 25) / 5 + 10 = 25.0
Security Features
🛡️ Input Validation
Only allows safe mathematical characters (0-9, +, -, *, /, (, ), ., space).
⚡ Safe Evaluation
Pre-filters input before using eval() to prevent code injection.
🚨 Error Handling
Catches division by zero, syntax errors, and invalid operations gracefully.
Advanced Features
🔧 Multiple Tools
- •
calculate()
- Core math operations - •
get_help()
- User assistance - •
validate_expression()
- Input checking
🎯 System Prompt
Guides the agent on when to use which tool based on user needs.
Try It Yourself
Download Complete Example
Complete calculator with security features and error handling