Implement Tool Idempotency and Validation

Medium
Agents

Idempotency in Tool Execution

Idempotent tools produce the same result when called multiple times with the same args.

Task

Implement IdempotentToolExecutor that:

  1. Caches tool results by (tool_name, args) hash.
  2. Returns cached result on repeated calls if idempotent=True.
  3. Validates arguments against a JSON Schema subset.
  4. Logs all executions (cached vs fresh).

Constraints

  • Hash must be stable (sorted keys, deterministic JSON).
  • Validation checks: required fields, type correctness (str/int/float/bool/list).
  • Non-idempotent tools always execute fresh (e.g., send_email).

Examples

Example 1:
Input: exec = IdempotentToolExecutor() call_count = 0 def counter(**k): global call_count; call_count += 1; return call_count exec.execute('counter', counter, {'x': 1}) exec.execute('counter', counter, {'x': 1}) call_count
Output: 1
Explanation: Second call with same args returns cached result; function only called once.

Starter Code

from typing import Any, Dict, Optional
import hashlib
import json

class IdempotentToolExecutor:
    def __init__(self):
        self.cache: Dict[str, Any] = {}
        self.execution_log: list = []

    def _compute_key(self, tool_name: str, args: Dict) -> str:
        # TODO: Create stable hash of tool name + sorted args
        pass

    def execute(self, tool_name: str, fn: callable, args: Dict,
                idempotent: bool = True) -> Dict:
        # TODO: Check cache if idempotent, execute, return result+metadata
        pass

    def validate_args(self, args: Dict, schema: Dict) -> list:
        # TODO: Validate args against JSON Schema (type, required)
        # Return list of validation errors
        pass

    def clear_cache(self, tool_name: Optional[str] = None) -> None:
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews