Introduction
Errors can happen when tools are used in AI agents. Handling these errors helps the agent keep working smoothly without crashing.
Jump into concepts and practice - no test required
try: result = tool.call(input_data) except ToolError as e: handle_error(e) result = fallback_value
try: response = weather_tool.get_forecast('New York') except ToolError: response = 'Sorry, I cannot get the weather now.'
try: data = file_tool.read('data.txt') except FileNotFoundError: data = '' # Use empty data if file missing
class ToolError(Exception): pass def tool_call(x): if x < 0: raise ToolError('Negative input not allowed') return x * 2 try: output = tool_call(-1) except ToolError as e: print(f'Error caught: {e}') output = 0 print(f'Result: {output}')
try-except blocks when calling external tools in an AI agent?try and except blocks to catch errors.try and except, not catch, error, or fail.try:
result = tool_call('data')
except Exception:
result = 'Fallback result'
print(result)
If tool_call raises an error, what will be printed?tool_call raises an error, the except block runs and sets result to 'Fallback result'.print(result) prints the fallback string.try:
output = tool_call()
except Exception as e
print('Error:', e)
output = None
print(output)
What is the error in this code?