🛡️ Building Resilient Autonomous Systems: Error Handling, Retries and Sandboxed Execution
Autonomous agents frequently encounter runtime friction: external API rate limits, malformed JSON tool arguments, syntax errors in generated code, and network timeouts. Without robust error handling and isolation, a single bad LLM tool call can crash the application or execute malicious code on host infrastructure. Robust Error Handling, Retries & Tool Sandbox Execution establishes defensive architectural layers including exponential backoff retry policies, Pydantic fallback parsing, circuit breakers, and secure containerized execution sandboxes (Docker).
📊 End-to-End Agentic Error Recovery & Sandbox Execution Workflow Diagram
1. Tool Call Generation
Agent formulates tool execution payload or Python script.
2. Validation & Sandbox
Validates schema or routes execution to secure Docker container.
3. Execution & Exception Check
Monitors execution for timeouts, syntax errors, or exceptions.
4. Exception Catch & Fix
Catches stack trace; feeds error back to LLM for self-correction.
5. Exponential Backoff
Retries failed API calls with jittered exponential delay.
6. Resilient Output / Fallback
Returns successful execution observation or graceful fallback.
import docker
client = docker.from_env()
def execute_code_in_docker_sandbox(python_code: str) -> str:
try:
container = client.containers.run(
image="python:3.11-slim",
command=["python", "-c", python_code],
detach=False,
mem_limit="256m",
network_disabled=True,
timeout=10
)
return container.decode("utf-8")
except Exception as e:
return f"Sandbox Execution Error: {str(e)}"
output = execute_code_in_docker_sandbox("print(2 + 2)")
print("Sandbox Output:", output)
tenacity library to handle transient HTTP 429 rate-limit errors from banking APIs.
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import requests
class RateLimitException(Exception):
pass
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type(RateLimitException)
)
def fetch_banking_endpoint(url: str):
response = requests.get(url)
if response.status_code == 429:
raise RateLimitException("API Rate Limit Exceeded")
return response.json()
print("Decorator initialized successfully for banking API calls.")
import json
from pydantic import BaseModel, ValidationError
class CartItem(BaseModel):
item_id: str
quantity: int
price: float
def parse_llm_cart_output(raw_json_str: str) -> CartItem:
try:
data = json.loads(raw_json_str)
return CartItem(**data)
except (json.JSONDecodeError, ValidationError) as e:
print(f"[Error Recovery] Malformed cart payload detected: {e}. Applying fallback schema.")
return CartItem(item_id="DEFAULT_ITEM", quantity=1, drice=0.0)
valid_item = parse_llm_cart_output('{"item_id": "SKU-102", "quantity": 2, "price": 19.99}')
print("Parsed Cart Item:", valid_item)
import time
class CircuitBreaker:
def __init__(self, failure_threshold: int = 3, recovery_timeout: float = 5.0):
self.threshold = failure_threshold
self.timeout = recovery_timeout
self.failures = 0
self.state = "CLOSED"
self.last_failure_time = 0
def record_failure(self):
self.failures += 1
if self.failures >= self.threshold:
self.state = "OPEN"
self.last_failure_time = time.time()
print("[Circuit Breaker] Threshold reached. State transitioned to OPEN.")
def allow_request(self) -> bool:
if self.state == "OPEN":
if time.time() - self.last_failure_time > self.timeout:
self.state = "HALF-OPEN"
return True
return False
return True
cb = CircuitBreaker()
cb.record_failure()
cb.record_failure()
cb.record_failure()
print("Allow EHR Request:", cb.allow_request())
import requests
def fetch_gps_coordinates_with_fallback(shipment_id: str) -> dict:
try:
response = requests.get(f"https://api.carrier.com/gps/{shipment_id}", timeout=2.0)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
print("[Fallback] Carrier GPS API timed out. Using last known interpolated coordinates.")
return {"lat": 34.0522, "lon": -118.2437, "status": "Interpolated Estimate"}
print(fetch_gps_coordinates_with_fallback("SHP-991"))
class AgentSafetyMonitor:
def __init__(self, max_steps: int = 5):
self.max_steps = max_steps
self.step_count = 0
def step(self):
self.step_count += 1
if self.step_count > self.max_steps:
raise RuntimeError("Maximum agent step quota exceeded. Halting infinite loop.")
return f"Executing step {self.step_count}/{self.max_steps}"
monitor = AgentSafetyMonitor(max_steps=2)
print(monitor.step())
print(monitor.step())
try:
print(monitor.step())
except RuntimeError as e:
print("Caught Guardrail Exception:", e)
class OCRException(Exception):
pass
def perform_robust_ocr(image_path: str) -> str:
try:
# Simulate primary OCR extraction failure on noisy scan
raise OCRException("Low contrast blur detected")
except OCRException:
print("[Recovery] Primary OCR failed. Applying OpenCV contrast normalization & grayscale conversion.")
# Simulated successful OCR after image preprocessing
return "Recovered Text: Confidential Settlement Agreement Section 8."
print(perform_robust_ocr("scans/doc_44.pdf"))
import sqlite3
def execute_generated_sql_with_self_correction(conn: sqlite3.Connection, bad_sql: str) -> str:
cursor = conn.cursor()
for attempt in range(2):
try:
cursor.execute(bad_sql if attempt == 0 else "SELECT student_id, score FROM exams")
return "SQL Executed Successfully."
except sqlite3.OperationalError as e:
print(f"[SQL Correction] Error: {e}. Prompting LLM to fix syntax...")
bad_sql = "SELECT student_id, score FROM exams"
return "Query failed after correction attempts."
conn = sqlite3.connect(":memory:")
print(execute_generated_sql_with_self_correction(conn, "SELCT * FROM exams"))