Tool Execution Loop with Configurable Error Policies

Medium
Agents

Tool Execution Loop with Error Policies

Agents call tool sequences where each step may fail. Configurable error policies allow resilience without losing critical guarantees.

Task

Implement ToolExecutionLoop that:

  1. Executes tools in order from a plan.
  2. retry: Re-attempt with exponential backoff; FAILED and continue after max_retries.
  3. skip: Log SKIPPED and continue immediately.
  4. abort: Stop all remaining tools (mark ABORTED).

Constraints

  • Backoff: 0.01 * 2**attempt seconds (capped at 1s for tests).
  • Unknown tools raise KeyError → treated as failure per policy.
  • Log contains one ToolResult per planned step.

Examples

Example 1:
Input: plan = [{'tool':'ok','args':{},'on_error':'skip'}, {'tool':'fail','args':{},'on_error':'skip'}] loop.execute(plan)
Output: [ToolResult(SUCCESS,...), ToolResult(SKIPPED,...)]
Explanation: First tool succeeds; second fails but policy is skip so pipeline continues.

Starter Code

from typing import Any, Dict, List, Optional, Callable
from dataclasses import dataclass
from enum import Enum

class ToolStatus(Enum):
    SUCCESS = 'success'
    FAILED = 'failed'
    SKIPPED = 'skipped'
    ABORTED = 'aborted'

@dataclass
class ToolResult:
    tool_name: str
    output: Any
    status: ToolStatus
    attempts: int
    error: Optional[str] = None

class ToolExecutionLoop:
    def __init__(self, tools: Dict[str, Callable], max_retries: int = 3):
        self.tools = tools
        self.max_retries = max_retries
        self.log: List[ToolResult] = []

    def execute(self, plan: List[Dict]) -> List[ToolResult]:
        # plan: [{'tool': str, 'args': dict, 'on_error': 'retry'|'skip'|'abort'}]
        pass

    def _run_one(self, name: str, args: Dict, on_error: str) -> ToolResult:
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews