Build AI Apps with Python: Tool Error Handling — Make Tools Bulletproof | Episode 11
Video: Build AI Apps with Python: Tool Error Handling — Make Tools Bulletproof | Episode 11 by Taught by Celeste AI - AI Coding Coach
Watch full page →Build AI Apps with Python: Tool Error Handling — Make Tools Bulletproof
In this episode, we focus on making your Python tools robust by implementing comprehensive error handling. By wrapping tool functions with try/except blocks, validating inputs, and using error dictionaries instead of raw exceptions, you can prevent your entire application from crashing due to common issues like missing files or division by zero.
Code
def read_file(path):
# Validate input path
if not path or ".." in path:
return {"error": "Invalid file path provided."}
try:
with open(path, "r") as file:
return {"content": file.read()}
except FileNotFoundError:
return {"error": f"File not found: {path}"}
except Exception as e:
return {"error": f"Unexpected error: {str(e)}"}
def divide(a, b):
# Check for zero division
if b == 0:
return {"error": "Division by zero is not allowed."}
try:
result = a / b
return {"result": result}
except Exception as e:
return {"error": f"Unexpected error: {str(e)}"}
def write_and_read(path, content):
# Validate path before writing
if not path or ".." in path:
return {"error": "Invalid file path provided."}
try:
with open(path, "w") as file:
file.write(content)
return read_file(path) # Reuse read_file to confirm write success
except Exception as e:
return {"error": f"Failed to write/read file: {str(e)}"}
# Example usage demonstrating error handling and recovery
result = read_file("missing.txt")
if "error" in result:
print("Error:", result["error"])
result = divide(10, 0)
if "error" in result:
print("Error:", result["error"])
# Recover by dividing by a valid number
result = divide(10, 2)
if "result" in result:
print("Recovered result:", result["result"])
result = write_and_read("example.txt", "Hello, world!")
if "content" in result:
print("File content:", result["content"])
Key Points
- Wrap every tool function in try/except blocks to catch and handle errors gracefully.
- Validate inputs such as file paths and divisor values to prevent common runtime errors.
- Return error information as dictionaries instead of raising exceptions to simplify error handling downstream.
- Use clear and descriptive error messages to aid debugging and user feedback.
- Design your tools so normal operation continues unaffected even if some calls fail.