Velamuvi AIAcademy

Lesson 7 of 9 · Doing It Well

Handling Tool Errors

Make LLM tool calling robust: catch exceptions, retry temporary failures with backoff, return clear errors with is_error, escalate to people and hide internals.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Sort tool failures into temporary errors, fixable errors and serious problems
  • Retry temporary failures in code, with backoff
  • Return errors to the model in a form it can act on
  • Keep secrets and internal details out of error messages

Tools fail. Plan for it.

Tools call networks, databases and other services, so failures are normal: timeouts, rate limits, missing records, expired credentials. The goal is that no failure crashes the conversation and that each one is handled by the right party.

Kind of failureExamplesWho handles it
TemporaryTimeout, HTTP 429 (rate limit), 503 (unavailable)Your code: retry with backoff
Fixable by the modelUnknown ID, invalid argument, HTTP 400 or 404The model: return a clear error so it can correct the call
SeriousExpired credentials (401), no permission (403), bugA person: stop, log and alert

A safe wrapper for every tool

This wrapper always returns a result, never an exception. It retries temporary errors itself, and turns other errors into messages the model can use. (This demo prints the backoff waits instead of actually sleeping.)

Try it yourselfPython
import json

class TemporaryError(Exception):
    """Worth retrying: timeouts, rate limits, a server that's briefly down."""

# ---- A flaky tool: fails twice with a timeout, then works ----
attempts = {"count": 0}
def get_stock_price(symbol):
    attempts["count"] += 1
    if symbol not in {"ACME", "GLOBX"}:
        raise KeyError(symbol)
    if attempts["count"] < 3:
        raise TemporaryError("timed out after 5 s")
    return {"symbol": symbol, "price": 182.4, "currency": "USD"}

def run_tool_safely(fn, args, retries=3):
    """Run a tool and ALWAYS return a tool_result-style dictionary, never an exception."""
    for attempt in range(1, retries + 1):
        try:
            return {"content": json.dumps(fn(**args)), "is_error": False}
        except TemporaryError as e:
            print(f"   attempt {attempt}: {e} (retrying after {2 ** (attempt - 1)} s)")   # backoff: 1 s, 2 s, 4 s
        except KeyError as e:
            return {"content": f"Unknown symbol {e}. Use a ticker symbol such as ACME.", "is_error": True}
        except Exception:
            return {"content": "The tool failed unexpectedly. Try again later or tell the user.", "is_error": True}
    return {"content": "The price service is not responding. Tell the user to try again later.", "is_error": True}

print("Call 1:", run_tool_safely(get_stock_price, {"symbol": "ACME"}))
print("Call 2:", run_tool_safely(get_stock_price, {"symbol": "Acme Corporation"}))

The first call hit two timeouts, retried, and succeeded on the third attempt. The model never saw the timeouts, and didn't need to. The second call used a company name instead of a ticker symbol: that's a mistake the model can fix, so the error says exactly what's expected.

Telling the model it was an error

Anthropic's API lets a tool result be marked as an error:

{"type": "tool_result", "tool_use_id": call.id, "content": "Unknown symbol 'Acme Corporation'. Use a ticker symbol such as ACME.", "is_error": True}

With other APIs, put a clear error field or sentence in the output. Either way, a good error message:

  • says what went wrong in plain words;
  • says how to fix it when the model can (“Use a ticker symbol such as ACME”);
  • says what to tell the user when it can't (“The price service is down; suggest trying later”).

Common mistakes

Practice exercise

Different failures need different handling. Route each HTTP error to the right action.

Your solutionPython
def action_for(status):
    # Decide what to do when a tool's API call fails with an HTTP status code:
    #   429 or 503        -> "retry"          (rate limited / briefly unavailable)
    #   400 or 404        -> "tell the model" (bad arguments: the model can fix them)
    #   401 or 403        -> "alert a person" (credentials or permissions problem)
    return "?"

for status in [503, 404, 401, 429, 400]:
    print(status, action_for(status))
Knowledge check

A tool's API call times out. Who should usually retry it?

Summary

  • Sort failures: temporary (retry in code), fixable (tell the model), serious (alert a person).
  • Wrap every tool so it always returns a result, never an exception.
  • Return errors with what went wrong and how to fix it, marked as errors where the API allows.
  • Use timeouts, retry limits and backoff, and never leak internal details.

Next: choosing tools when there are dozens of them.

Finished reading? Tick it off to track your progress.