Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 20 min · revision 3

Recovering from Failed Actions

Turn tool failures into structured observations, retry only what is safe to retry, fall back to a second source, and stop with a clear failure report when recovery is impossible.

Contentsand lesson path

What you will learn

  • Recover from tool errors and malformed calls without losing the task, and report a clear failure when recovery is impossible.

Prerequisites: Tool Calling

01. Tool Failures as Informational Signals, Not Fatal Exceptions

In ordinary code, an unhandled exception stops the program. In an agent loop that is expensive: if an eight-step task crashes on step six because of a brief network fault, the work of the first five steps is lost.

Many tool failures are transient, such as a timeout, a 429 rate limit or a short 503. Others are not, and retrying them wastes time. So the runtime catches every tool error, decides what kind it is, and returns it to the model as a structured observation: a tool result that describes the error. The model can then retry, switch tools or fix its arguments.

Tool failures fall into three groups:

  • Transient faults: dropped connections, HTTP 503, rate limits (HTTP 429), an exhausted connection pool. A retry with backoff, or a second endpoint, often fixes them.
  • Invalid arguments: text that is not valid JSON, or valid JSON that breaks a domain rule, such as an unknown customer ID or a negative amount. Return the error as the tool result; the model has to change the call, because the same call fails again.
  • Missing prerequisites or access: the resource does not exist (a deleted record, a parent object not created yet), or the caller may not use it (an expired token). These need a different plan or a person.

02. Architectural Patterns for Dynamic Self-Correction

Once an error observation reaches the model, recovery needs two things: enough information to choose a next step, and an alternative to choose. Three patterns help:

  1. Informative errors. Instead of "Internal Server Error", return the status code, whether the failure is transient and which fallback exists, for example {"error": "Vendor API unavailable (HTTP 503)", "transient": true, "fallback_available": "query_vendor_cache"}. Then a model can tell an outage from a bad argument.
  2. Fallback tools. For a critical capability, offer a second source, such as a read-only cache or replica that serves slightly stale but acceptable data.
  3. Adapting arguments. When a query returns nothing (no invoices in a narrow date range), the model can widen the filter and try again on the next turn.

Retries and idempotency. Only retry automatically when the operation is idempotent: a read, or a write that carries an idempotency key the server uses to drop duplicates. A timeout on a non-idempotent write (a payment, a ticket, an email) does not mean it failed: the server may have done it, and a blind retry can pay twice. For such a write the wrapper marks the error retryable: false and tells the model to check the status by idempotency key before doing anything else. The wrapper below implements these rules.

Python · recovery-lab/tool_wrapper.py
"""Turns every tool outcome into a JSON observation the model can act on."""
import json
import re
import time
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError

TRANSIENT_HTTP = {429, 500, 502, 503, 504}
SECRET = re.compile(r"(api_key|token|password)=[^&\s]+")


def redact(text):
    return SECRET.sub(r"\1=<redacted>", text)  # hide known secret parameters


def retry_after(headers, default=1.0):
    """Retry-After is either seconds or an HTTP date (RFC 9110)."""
    value = headers.get("Retry-After") if headers else None
    if value is None:
        return default
    try:
        return max(0.0, float(value))
    except ValueError:
        try:
            return max(0.0, parsedate_to_datetime(value).timestamp() - time.time())
        except (TypeError, ValueError):
            return default


def classify(exc):
    """Returns (code, transient, retry_after_s)."""
    if isinstance(exc, HTTPError):
        return f"HTTP_{exc.code}", exc.code in TRANSIENT_HTTP, retry_after(exc.headers)
    if isinstance(exc, (TimeoutError, ConnectionError)):
        return type(exc).__name__, True, 1.0
    return type(exc).__name__, False, 0.0  # validation and unknown errors


def safe_tool_executor(tool_fn, tool_name, kwargs, idempotent, retries=2):
    for attempt in range(retries + 1):
        try:
            result = tool_fn(**kwargs)
            return json.dumps({"status": "success", "data": result}, default=str)
        except Exception as exc:  # the loop must never see a raw exception
            code, transient, wait = classify(exc)
            if transient and idempotent and attempt < retries:
                time.sleep(min(wait, 2.0) * 0.05)  # scaled down for the lab
                continue
            retryable = transient and idempotent
            rejected = code.startswith("HTTP_4") or code in ("ValueError", "TypeError")
            if not idempotent and not rejected:
                # timeout, 5xx or unknown failure of a write: it may have happened
                advice = "Outcome unknown: check status by idempotency key first."
            elif retryable:
                advice = "Still failing after retries: use a fallback tool."
            elif transient:  # a 429 on a write: refused, so not done, not retried
                advice = "Refused (rate limit), not retried: wait, then call once more."
            else:
                advice = "Do not retry unchanged: fix the arguments or stop."
            return json.dumps({
                "status": "error", "tool": tool_name, "code": code,
                "message": redact(str(exc))[:200], "attempts": attempt + 1,
                "retryable": retryable, "recommendation": advice,
            })

03. When recovery is impossible

Recovery has limits, and the loop, not the model, should decide when they are reached. A model told "use a fallback tool" may keep calling that fallback turn after turn, as the lab shows. Three rules cover most cases:

  1. No fallback left. Every tool that can provide a capability (here, the vendor API and its cache) has failed after its own retries.
  2. A permanent error. Some errors cannot be fixed by a retry or by new arguments: an expired or revoked credential (HTTP 401), a missing permission (HTTP 403), an endpoint that has been retired. Stop at the first one, because a person has to act.
  3. Budget spent. The step cap, token budget or deadline from the limits lab ran out before the goal was reached.

When a rule fires, the loop returns a failure report instead of an answer. A useful report holds the goal, the rule that stopped the run, the steps that finished with their data (the partial result), the last errors with secrets removed, and one concrete next step for a person. Leave out stack traces and raw URLs: they can leak secrets and do not say what to do. Do not fill the gap with a guess: a confident answer built without the missing data is worse than a clear "not done".

04. Lab: Invoice Reconciliation with Injected Faults

An agent reconciles invoice inv_44: parse it, look up the vendor, match the line items and post the payment. Two faults are switched on. The vendor API returns HTTP 503, so the agent must fall back to a cached replica. The bank call times out after it has already recorded the payment, so a blind retry would pay twice. Run 2 also takes the cache down and run 3 hits an expired bank token; in both, recovery is impossible and the loop must say so.

You need: Python 3.12 or later; standard library only, no API key. Tested with Python 3.12.13. Create a folder recovery-lab, save tool_wrapper.py from the section above into it, and add the files below. The model is a scripted stand-in, so the run is repeatable.

Step 1: fixture tools. FAULTS switches the failures on and off (fault injection). LEDGER is what the bank really recorded, so you can check for double payments. Each tool is registered with an idempotent flag; post_payment is the only write.

Python · recovery-lab/tools.py
"""Fixture tools for invoice reconciliation, with switchable faults."""
from urllib.error import HTTPError

FAULTS = {"vendor_api_down": True, "cache_down": False, "payment_timeout": True,
          "bank_token_expired": False}
LEDGER = []  # payments the "bank" really recorded


def parse_invoice(path):
    return {"id": "inv_44", "vendor_id": "v_99", "total": "1180.00"}


def query_vendor(vendor_id):
    if FAULTS["vendor_api_down"]:
        url = f"https://vendors.example/v1/{vendor_id}?api_key=sk_live_123"
        raise HTTPError(url, 503, f"Service Unavailable: {url}", None, None)
    return {"vendor_id": vendor_id, "name": "Acme Corp"}


def query_vendor_cache(vendor_id):
    if FAULTS["cache_down"]:
        raise ConnectionError("cache replica refused the connection")
    return {"vendor_id": vendor_id, "name": "Acme Corp", "stale_s": 540}


def match_line_items(invoice_id):
    return {"invoice_id": invoice_id, "matched": 4, "unmatched": 0}


def post_payment(invoice_id, amount, idempotency_key):
    if float(amount) <= 0:  # a bad argument: refused before anything is recorded
        raise ValueError(f"amount must be positive, got {amount}")
    if FAULTS["bank_token_expired"]:  # rejected before anything is recorded
        raise HTTPError("https://bank.example/v2/payments", 401,
                        "Unauthorized: API token expired", None, None)
    if any(p["key"] == idempotency_key for p in LEDGER):
        return {"duplicate_ignored": True}  # the server deduplicates by key
    LEDGER.append({"key": idempotency_key, "invoice": invoice_id, "amount": amount})
    if FAULTS["payment_timeout"]:
        FAULTS["payment_timeout"] = False
        raise TimeoutError("no response from bank within 10s")  # but it was posted
    return {"posted": True}


def get_payment_status(idempotency_key):
    return {"posted": any(p["key"] == idempotency_key for p in LEDGER)}


# name -> (function, idempotent?)
TOOLS = {
    "parse_invoice": (parse_invoice, True),
    "query_vendor": (query_vendor, True),
    "query_vendor_cache": (query_vendor_cache, True),
    "match_line_items": (match_line_items, True),
    "post_payment": (post_payment, False),  # a write: never auto-retried
    "get_payment_status": (get_payment_status, True),
}

Step 2: the scripted model and the loop. The model function reads the history of tool results and picks the next call. It follows the advice to use a fallback and never gives up on its own; a real model can behave the same way when every error message suggests another try. The loop applies the three stop rules after every tool result: stop_reason() checks for a permanent error and for a capability with no source left, and the step cap covers the budget. failure_report() builds the report described above. It replaces any URL in the last error message with <url>, because the report goes to a person and the tool name already says which service failed.

Python · recovery-lab/fake_model.py
"""A scripted stand-in for the model: picks the next call from the history."""


def next_action(history):
    done = {h["tool"]: h["result"] for h in history}
    last = history[-1]["result"] if history else None
    if "parse_invoice" not in done:
        return ("parse_invoice", {"path": "inv_44.pdf"})
    if "query_vendor" not in done:
        return ("query_vendor", {"vendor_id": "v_99"})
    vendor_ok = any(done.get(t, {}).get("status") == "success"
                    for t in ("query_vendor", "query_vendor_cache"))
    if not vendor_ok:  # follows the advice; it never decides to give up by itself
        return ("query_vendor_cache", {"vendor_id": "v_99"})
    if "match_line_items" not in done:
        return ("match_line_items", {"invoice_id": "inv_44"})
    pay = {"invoice_id": "inv_44", "amount": "1180.00", "idempotency_key": "pay-inv_44"}
    if "post_payment" not in done:
        return ("post_payment", pay)
    if last["status"] == "error" and "idempotency key" in last["recommendation"]:
        return ("get_payment_status", {"idempotency_key": "pay-inv_44"})
    return ("finish", {})
Python · recovery-lab/run_lab.py
"""Runs the reconciliation three times; the loop decides when recovery is over."""
import json
import re
import sys

import tools
from fake_model import next_action
from tool_wrapper import safe_tool_executor

GOAL = "reconcile invoice inv_44 and pay it"
FALLBACKS = {"vendor": ("query_vendor", "query_vendor_cache")}
STOP_CODES = {"HTTP_401", "HTTP_403"}  # credentials: no retry or fallback fixes these
URL = re.compile(r"https?://\S+")  # a report names the tool, not the endpoint


def short(r):
    if r["status"] == "success":
        return f"ok {json.dumps(r['data'])[:52]}"
    pad = "\n      "
    return (f"{r['code']} after {r['attempts']} attempt(s), retryable={r['retryable']}"
            f"{pad}{r['message'][:60]}{pad}-> {r['recommendation']}")


def stop_reason(history, rules=True):
    """(reason, next step for a person) once recovery is impossible, else None."""
    last = history[-1]
    if not rules or last["result"]["status"] == "success":
        return None
    if last["result"]["code"] in STOP_CODES:
        return (f"permanent error: {last['tool']} returned {last['result']['code']}",
                f"renew the credentials used by {last['tool']}, then re-run")
    failed = {h["tool"] for h in history if h["result"]["status"] == "error"}
    for capability, options in FALLBACKS.items():
        if last["tool"] in options and failed >= set(options):
            return (f"no {capability} source left: every option failed",
                    f"restore {' or '.join(options)}, then re-run")
    return None


def failure_report(history, reason, next_step):
    ok = [h for h in history if h["result"]["status"] == "success"]
    errors = [h["result"] for h in history if h["result"]["status"] == "error"]
    return {"status": "failed", "goal": GOAL, "stop_reason": reason,
            "partial": {h["tool"]: h["result"]["data"] for h in ok},
            "last_errors": [f"{e['tool']}: {e['code']}" for e in errors[-2:]],
            "message": URL.sub("<url>", errors[-1]["message"])[:60],
            "next_step": next_step}


def show(report):
    for key, value in report.items():
        if key == "partial":  # one line per finished step, with its data
            for tool, data in value.items():
                print(f"  partial.{tool}: {json.dumps(data)}")
        else:
            print(f"  {key}: {json.dumps(value)}")


def run(max_steps=8, rules=True):
    history = []
    for step in range(1, max_steps + 1):
        name, args = next_action(history)
        if name == "finish":
            return {"status": "done", "steps": len(history)}
        fn, idempotent = tools.TOOLS[name]
        result = json.loads(safe_tool_executor(fn, name, args, idempotent))
        history.append({"tool": name, "result": result})
        print(f"[{step}] {name}: {short(result)}")
        stop = stop_reason(history, rules)
        if stop:
            return failure_report(history, *stop)
    return failure_report(history, f"step budget of {max_steps} spent",
                          "read the trace before raising the budget")


rules = "--no-stop-rules" not in sys.argv
print("== run 1: vendor API down, payment call times out")
show(run(rules=rules))
print("  bank ledger:", json.dumps(tools.LEDGER))
print("\n== run 2: vendor API and cache both down")
tools.FAULTS.update(cache_down=True)
show(run(rules=rules))
print("\n== run 3: vendor API back, bank token expired")
tools.FAULTS.update(vendor_api_down=False, cache_down=False, bank_token_expired=True)
show(run(rules=rules))
print("  payments in the ledger:", len(tools.LEDGER))
Terminal
python3 run_lab.py
Expected output
== run 1: vendor API down, payment call times out
[1] parse_invoice: ok {"id": "inv_44", "vendor_id": "v_99", "total": "1180
[2] query_vendor: HTTP_503 after 3 attempt(s), retryable=True
      HTTP Error 503: Service Unavailable: https://vendors.example
      -> Still failing after retries: use a fallback tool.
[3] query_vendor_cache: ok {"vendor_id": "v_99", "name": "Acme Corp", "stale_s"
[4] match_line_items: ok {"invoice_id": "inv_44", "matched": 4, "unmatched": 
[5] post_payment: TimeoutError after 1 attempt(s), retryable=False
      no response from bank within 10s
      -> Outcome unknown: check status by idempotency key first.
[6] get_payment_status: ok {"posted": true}
  status: "done"
  steps: 6
  bank ledger: [{"key": "pay-inv_44", "invoice": "inv_44", "amount": "1180.00"}]

== run 2: vendor API and cache both down
[1] parse_invoice: ok {"id": "inv_44", "vendor_id": "v_99", "total": "1180
[2] query_vendor: HTTP_503 after 3 attempt(s), retryable=True
      HTTP Error 503: Service Unavailable: https://vendors.example
      -> Still failing after retries: use a fallback tool.
[3] query_vendor_cache: ConnectionError after 3 attempt(s), retryable=True
      cache replica refused the connection
      -> Still failing after retries: use a fallback tool.
  status: "failed"
  goal: "reconcile invoice inv_44 and pay it"
  stop_reason: "no vendor source left: every option failed"
  partial.parse_invoice: {"id": "inv_44", "vendor_id": "v_99", "total": "1180.00"}
  last_errors: ["query_vendor: HTTP_503", "query_vendor_cache: ConnectionError"]
  message: "cache replica refused the connection"
  next_step: "restore query_vendor or query_vendor_cache, then re-run"

== run 3: vendor API back, bank token expired
[1] parse_invoice: ok {"id": "inv_44", "vendor_id": "v_99", "total": "1180
[2] query_vendor: ok {"vendor_id": "v_99", "name": "Acme Corp"}
[3] match_line_items: ok {"invoice_id": "inv_44", "matched": 4, "unmatched": 
[4] post_payment: HTTP_401 after 1 attempt(s), retryable=False
      HTTP Error 401: Unauthorized: API token expired
      -> Do not retry unchanged: fix the arguments or stop.
  status: "failed"
  goal: "reconcile invoice inv_44 and pay it"
  stop_reason: "permanent error: post_payment returned HTTP_401"
  partial.parse_invoice: {"id": "inv_44", "vendor_id": "v_99", "total": "1180.00"}
  partial.query_vendor: {"vendor_id": "v_99", "name": "Acme Corp"}
  partial.match_line_items: {"invoice_id": "inv_44", "matched": 4, "unmatched": 0}
  last_errors: ["post_payment: HTTP_401"]
  message: "HTTP Error 401: Unauthorized: API token expired"
  next_step: "renew the credentials used by post_payment, then re-run"
  payments in the ledger: 1

In run 1 the wrapper retried the 503 twice on its own, because a vendor lookup is a read, then told the model to use a fallback. The payment timeout was not retried: the model checked the status by idempotency key, found the payment and stopped. The ledger holds exactly one payment.

In run 2 both vendor sources fail, so the no-fallback rule ends the run after three steps. In run 3 the bank rejects the payment with 401. The server answered and refused, so the wrapper does not report an unknown outcome, and the permanent-error rule stops the run at once. The report keeps the three finished steps and names the fix.

Now run python3 run_lab.py --no-stop-rules. Before you do, predict what run 2 prints. The model keeps calling the cache until the step cap, and the report says step budget of 8 spent: the budget still stops the run, but only after five wasted calls and a less useful next step. Run 3 is worse: the model treats the refused payment as finished and the run reports status: "done", a false success that the permanent-error rule prevents.

Step 3: negative tests. These tests cover the cases that cause real damage: a 503 is retryable, a 400 and a timed-out write are not retried, a write with an unknown outcome is checked by status first, a rejected write (401) is not reported as unknown, a rate-limited write (429) is not retried and is not told "after retries", and neither a Retry-After HTTP date (allowed by RFC 9110) nor a non-JSON result crashes the wrapper. A secret passed as an api_key, token or password parameter is redacted before the message reaches the model.

The last test sends two malformed calls to the real post_payment: a negative amount, which the tool refuses with ValueError, and a call without idempotency_key, which fails with TypeError before the tool body runs. Both come back after one attempt with "fix the arguments", and the ledger stays empty. The scripted model in this lab passes Python dicts, so a reply whose arguments are not valid JSON never reaches the wrapper; The Loop in Sixty Lines shows the json.loads branch that turns that case into a tool result too.

Python · recovery-lab/test_wrapper.py
"""Negative tests: the wrapper must classify, never double-write, never leak."""
import json
import unittest
from decimal import Decimal
from urllib.error import HTTPError

import tools
from tool_wrapper import safe_tool_executor


def failing(exc, calls):
    def tool(**kwargs):
        calls.append(kwargs)
        raise exc
    return tool


def http(code, url="https://api.example/v1/x"):
    return HTTPError(url, code, "upstream error", None, None)


class WrapperTests(unittest.TestCase):
    def run_tool(self, exc, idempotent=True, retries=2):
        calls = []
        out = safe_tool_executor(failing(exc, calls), "t", {}, idempotent, retries)
        return json.loads(out), len(calls)

    def test_503_is_retried_and_marked_retryable(self):
        out, calls = self.run_tool(http(503))
        self.assertEqual((out["code"], out["retryable"], calls), ("HTTP_503", True, 3))

    def test_400_is_not_retried(self):
        out, calls = self.run_tool(http(400))
        self.assertEqual((out["retryable"], calls), (False, 1))

    def test_write_timeout_is_never_retried(self):
        out, calls = self.run_tool(TimeoutError("slow"), idempotent=False)
        self.assertEqual((out["retryable"], calls), (False, 1))
        self.assertIn("idempotency key", out["recommendation"])

    def test_http_date_retry_after_does_not_crash(self):
        exc = HTTPError("https://x.example", 503, "busy",
                        {"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"}, None)
        out, calls = self.run_tool(exc)
        self.assertEqual((out["code"], calls), ("HTTP_503", 3))

    def test_unknown_error_on_write_says_check_status(self):
        out, calls = self.run_tool(OSError("socket closed"), idempotent=False)
        self.assertEqual(calls, 1)
        self.assertIn("idempotency key", out["recommendation"])

    def test_rejected_write_is_not_unknown(self):
        out, calls = self.run_tool(http(401), idempotent=False)
        self.assertEqual((out["retryable"], calls), (False, 1))
        self.assertNotIn("idempotency key", out["recommendation"])

    def test_rate_limited_write_is_not_retried(self):
        out, calls = self.run_tool(http(429), idempotent=False)
        self.assertEqual((out["retryable"], calls), (False, 1))
        self.assertNotIn("after retries", out["recommendation"])

    def test_secrets_are_redacted(self):
        exc = ValueError("bad call to https://x.example/?api_key=sk_live_999&a=1")
        out, _ = self.run_tool(exc)
        self.assertNotIn("sk_live_999", out["message"])

    def test_non_json_result_does_not_crash(self):
        out = safe_tool_executor(lambda: Decimal("1.10"), "t", {}, True)
        self.assertEqual(json.loads(out)["data"], "1.10")

    def test_malformed_payment_call_is_rejected_not_retried(self):
        tools.LEDGER.clear()
        bad = {"invoice_id": "inv_44", "amount": "-1180.00", "idempotency_key": "k1"}
        missing = {"invoice_id": "inv_44", "amount": "1180.00"}  # no key
        for args, code in ((bad, "ValueError"), (missing, "TypeError")):
            out = json.loads(safe_tool_executor(tools.post_payment, "post_payment",
                                                args, idempotent=False))
            self.assertEqual((out["code"], out["attempts"]), (code, 1))
            self.assertIn("fix the arguments", out["recommendation"])
        self.assertEqual(tools.LEDGER, [])


if __name__ == "__main__":
    unittest.main()
Terminal
python3 -m unittest test_wrapper
Illustrative output (the time on the "Ran 10 tests" line varies)
..........
----------------------------------------------------------------------
Ran 10 tests in 0.102s

OK

05. Practice questions

Practice check · 3 questions

Action failure recovery and fallback resilience check

Three scenario questions on unsafe retries and when to stop.

Q1. In one run the wrapper gets HTTP 503 from `query_vendor` and a timeout from `post_payment`. Which of the two does it retry on its own?
Q2. The lab's failure report is read by a person. Which of these should it leave out?
Q3. You run the lab with `--no-stop-rules`, and both vendor sources are down. What does run 2 print at the end?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add these rules to an agent loop of your own:

  • Wrap every tool call: catch timeouts, HTTP errors and validation errors at the tool interface, and redact secrets before the message reaches the model.
  • Return an error code, a transient flag and a recommendation, so the model knows what caused the error and what to try.
  • Offer a fallback source for each critical capability, and list the fallbacks in code so the loop can tell when none is left.
  • For 429 and 5xx errors on idempotent calls, retry with exponential backoff and honour Retry-After. Do not auto-retry a write without an idempotency key; check its status first.
  • Write the stop rules (no fallback left, permanent error, budget spent) and one failure-report format, then test that each rule fires.
  • Record every fallback and every stop in your traces.

07. Review prompt

Without looking back, explain why an agent loop turns tool exceptions into observations instead of crashing. Name the three stop rules and give an example error for each, then list what a failure report should contain and why it leaves out raw URLs and stack traces.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check