Skip to content

Handling Errors in LLM Agents: Retries, Fallbacks, and Degradation

Summary

Step-by-step instructions for building a resilient LLM agent: handling API errors, retries, model fallbacks, and graceful degradation.

Why Agents Fail

LLM agents rely on external APIs: models, tools, databases. Any failure—a timeout, rate limit, malformed JSON—can bring down the entire pipeline. Without error handling, the agent is unusable in production.

Error Classification

Type Example Strategy
Transient Timeout, 429, 5xx Retry with delay
Permanent 400, 401, 403 Fallback to another model
Logical Malformed JSON, empty response Regenerate with validation
Infrastructure No network, tool unavailable Degradation: skip step

Basic Retry with Exponential Backoff

import time
import random
from openai import OpenAI

client = OpenAI()

def call_with_retry(messages, max_retries=3, base_delay=1.0):
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="gpt-4o",
                messages=messages,
                timeout=30
            )
            return response.choices[0].message.content
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            delay = base_delay * (2 ** attempt) + random.uniform(0, 0.5)
            print(f"Attempt {attempt+1} failed: {e}. Retrying in {delay:.2f}s")
            time.sleep(delay)

Model Fallback

If a model consistently returns errors, switch to a backup.

MODELS = ["gpt-4o", "claude-3-5-sonnet", "deepseek-chat"]

def call_with_fallback(messages):
    last_error = None
    for model in MODELS:
        try:
            response = client.chat.completions.create(model=model, messages=messages, timeout=30)
            return response.choices[0].message.content
        except Exception as e:
            last_error = e
            print(f"Model {model} failed: {e}")
    raise last_error

Handling Malformed Output

Agents often require structured output. If the model returns invalid JSON, retry the request with an error message.

import json

def call_with_json_validation(messages, max_attempts=2):
    for attempt in range(max_attempts):
        content = call_with_retry(messages)
        try:
            return json.loads(content)
        except json.JSONDecodeError:
            if attempt == max_attempts - 1:
                raise
            messages.append({"role": "assistant", "content": content})
            messages.append({"role": "user", "content": "Response is not valid JSON. Return only JSON without explanations."})
    raise ValueError("Failed to get valid JSON")

Functional Degradation

When a tool is unavailable, the agent should continue to work with reduced functionality.

class Tool:
    def execute(self, query):
        raise NotImplementedError

class SearchTool(Tool):
    def execute(self, query):
        # simulate failure
        raise ConnectionError("Search API is down")

class Agent:
    def __init__(self):
        self.tools = {"search": SearchTool()}

    def run(self, task):
        try:
            result = self.tools["search"].execute(task)
            return result
        except ConnectionError:
            print("Search unavailable, using fallback")
            return self._fallback_response(task)

    def _fallback_response(self, task):
        return "Search temporarily unavailable. Try again later."

Timeouts and Cancellation

Set timeouts on each call to prevent the agent from hanging.

import asyncio

async def call_with_timeout(coro, timeout=10):
    try:
        return await asyncio.wait_for(coro, timeout=timeout)
    except asyncio.TimeoutError:
        print("Request timed out")
        return None

Logging and Monitoring

Each error should be logged with context.

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def log_error(step, error, context):
    logger.error(f"Step: {step}, Error: {error}, Context: {context}")

Practical Recommendations

  • Retry only for transient errors (429, 5xx, timeout).
  • Maximum 3–5 retries, then fallback.
  • For rate limit, use the Retry-After header from the response.
  • Validate output at each step of the agent.
  • Test failure scenarios with mock servers.