Tool Execution with Try-Catch

Easy
Agents

Implement safe tool execution with retry logic:

  1. Try to execute tool_func(**args)
  2. On exception, retry up to max_retries times
  3. If all retries fail, return fallback_value
  4. Track number of attempts made
  5. Capture last error message if failed

Requirements:

  • Wait 0.1 seconds between retries (use time.sleep)
  • Return structured result with all fields
  • 'error' should be string representation of last exception
  • 'attempts' counts total tries (initial + retries)

Examples

Example 1:
Input: safe_tool_execute(lambda x: x/0, {'x': 5}, max_retries=1, fallback_value='error')
Output: {'result': 'error', 'success': False, 'attempts': 2, 'error': 'division by zero'}
Explanation: Always fails, retries once (total 2 attempts), returns fallback
Example 2:
Input: safe_tool_execute(lambda x: x*2, {'x': 5}, max_retries=2)
Output: {'result': 10, 'success': True, 'attempts': 1, 'error': None}
Explanation: Succeeds on first try, no retries needed

Starter Code

def safe_tool_execute(tool_func, args, max_retries=2, fallback_value=None):
    """
    Execute a tool function with error handling and retries.
    
    Args:
        tool_func: Callable to execute
        args: Dict of arguments to pass
        max_retries: Number of retry attempts on failure
        fallback_value: Value to return if all retries fail
    
    Returns:
        dict with 'result', 'success' (bool), 'attempts', 'error' (if failed)
    """
    # Your implementation here
    pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews