Implement safe tool execution with retry logic:
- Try to execute tool_func(**args)
- On exception, retry up to max_retries times
- If all retries fail, return fallback_value
- Track number of attempts made
- 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
passPython3
ReadyLines: 1Characters: 0
Ready