Reliable Tool Execution and Error Recovery
Tools fail in ordinary ways. A good execution layer turns those failures into safe, understandable next steps.
Put one execution layer between the model and every tool. It validates the call, sets a deadline, retries only what is safe, protects state changes with idempotency keys, limits request rates, stops calling services that keep failing, checks results and returns a short, consistent envelope. When the outcome of an action is unknown, check before repeating it.
What you will learn: the execution pipeline, classifying failures, timeouts and retries, circuit breakers and rate limits, validating and shaping results, and recovering part-finished work.
Prerequisites: Agent Tools, Function Calling and Tool Registries. Distributed Systems, Networking and Databases explains idempotency in detail.
The execution pipeline
Centralizing this path means that a new tool inherits protections instead of reimplementing them. Individual tools declare what they need: whether they change state, whether repeats are safe, how long they may take and how large results may be.
Classify what went wrong
| Class | Examples | Right response |
|---|---|---|
| Invalid request | Missing field, bad date | Return the reason; let the model correct it once or twice |
| Not found | Unknown identifier | Search or ask; never invent another identifier |
| Not allowed | Missing permission | Stop and explain; do not hunt for another route |
| Temporary | Rate limit, brief outage | Retry later within limits |
| Permanent | Feature unavailable, account closed | Report and offer an alternative |
| Unknown outcome | Timeout on a write | Query status before any repeat |
The model should not have to infer the class from an exception name. Your layer knows more about the service than the model does, so let it decide and say what to do.
Return a consistent envelope
"""Turn raw outcomes into small, consistent results the agent can act on."""
import json
ADVICE = {
"invalid": "fix the arguments, then call again",
"not_found": "check the identifier; do not guess another",
"denied": "stop and tell the user",
"temporary": "try again later",
"unknown": "check status before doing anything else",
}
def classify(status, writes):
if status in (400, 422):
return "invalid"
if status == 404:
return "not_found"
if status in (401, 403):
return "denied"
if status is None or status >= 500: # None means no reply arrived
return "unknown" if writes else "temporary"
if status == 429:
return "temporary"
return "unknown"
def envelope(status, body=None, writes=False, max_items=3):
if status is not None and 200 <= status < 300:
items = body["items"]
return {"ok": True, "items": items[:max_items],
"total": len(items),
"truncated": len(items) > max_items}
kind = classify(status, writes)
return {"ok": False, "error": kind, "next": ADVICE[kind]}
big = {"items": [{"id": n, "note": "x" * 200} for n in range(1, 41)]}
small = envelope(200, {"items": [{"id": n} for n in range(1, 41)]})
print(json.dumps(small))
print("raw size:", len(json.dumps(big)),
"| shaped size:", len(json.dumps(small)))
for label, status, writes in [("search timed out", None, False),
("payment timed out", None, True),
("bad date", 422, False),
("rate limited", 429, True),
("no access", 403, False)]:
result = envelope(status, writes=writes)
print(f"{label:<18}{result['error']:<10} {result['next']}")
Output:
{"ok": true, "items": [{"id": 1}, {"id": 2}, {"id": 3}], "total": 40, "truncated": true}
raw size: 8962 | shaped size: 88
search timed out temporary try again later
payment timed out unknown check status before doing anything else
bad date invalid fix the arguments, then call again
rate limited temporary try again later
no access denied stop and tell the user
Forty records of nearly nine thousand characters became a small result that still tells the model the total and that more exist. The same missing reply is classified differently for a search and a payment: reading again is harmless, while paying again might not be. The rate-limited write is "temporary" because a 429 response normally means the request was not processed, but confirm that with each service. Status codes and their meaning vary between providers, so this mapping is a starting point to adapt per integration.
Make invalid-argument errors teach
When a call fails validation, name the field, say what was expected and, where safe, list allowed values. Compare "bad request" with "priority must be one of low, normal or high". The second usually gets a correct next call. Count how often each correction happens; a field that is regularly wrong is a design problem, and fixing the schema beats paying for repair turns on every task.
Timeouts and deadlines
- Set a timeout on every call, based on measured response times plus a margin.
- Pass a task deadline down, so that a tool does not start work that cannot finish in time.
- Cancel what you can, but remember that canceling the wait may not cancel the remote work.
- Move long work to jobs: start it, return an identifier and provide a status tool.
A job interface also stops the model from polling in a tight loop. Return a suggested waiting time and let the application, not the model, schedule the next check where possible.
Retries that help
| Rule | Reason |
|---|---|
| Retry only temporary failures | Invalid requests fail the same way again |
| Repeat writes only with idempotency protection | Prevents duplicate actions |
| Use exponential backoff with jitter | Spreads load while a service recovers |
| Cap attempts and total time | Keeps tasks bounded |
| Honor server retry hints | Respects published limits |
| Retry in one layer | Stops multiplication across SDK, executor and model |
Check what your software library already retries. If it makes three attempts and your executor makes three, a single model request can produce nine calls before the model even considers trying again.
Circuit breakers
When a dependency is down, continuing to call it wastes time and slows its recovery. A circuit breaker counts failures, then refuses calls for a cooling period, then lets a trial call through.
"""A circuit breaker stops calls to a service that keeps failing."""
class Breaker:
def __init__(self, threshold=3, cooldown=30):
self.threshold, self.cooldown = threshold, cooldown
self.failures, self.opened_at = 0, None
def state(self, now):
if self.opened_at is None:
return "closed"
return ("half-open" if now - self.opened_at >= self.cooldown
else "open")
def call(self, now, service):
state = self.state(now)
if state == "open":
return "skipped"
try:
service()
except ConnectionError:
self.failures += 1
if state == "half-open" or self.failures >= self.threshold:
self.opened_at = now
return "failed"
self.failures, self.opened_at = 0, None
return "ok"
def make_service(now):
def service():
if 10 <= now < 60: # simulated outage
raise ConnectionError
return service
breaker, sent = Breaker(), 0
for now in range(0, 101, 5): # one request every 5 seconds
before = breaker.state(now)
result = breaker.call(now, make_service(now))
sent += result != "skipped"
after = breaker.state(now)
if result != "ok" or before != after:
print(f"t={now:>3} {before:<9} {result:<7} -> {after}")
print(f"requests: 21, sent to the service: {sent}")
Output:
t= 10 closed failed -> closed
t= 15 closed failed -> closed
t= 20 closed failed -> open
t= 25 open skipped -> open
t= 30 open skipped -> open
t= 35 open skipped -> open
t= 40 open skipped -> open
t= 45 open skipped -> open
t= 50 half-open failed -> open
t= 55 open skipped -> open
t= 60 open skipped -> open
t= 65 open skipped -> open
t= 70 open skipped -> open
t= 75 open skipped -> open
t= 80 half-open ok -> closed
requests: 21, sent to the service: 11
After three failures the breaker opened and skipped calls. A trial at 50 seconds failed and restarted the wait; the next trial succeeded. Only 11 of 21 requests reached the service. The cost is visible too: the service recovered at 60 seconds but was not used again until 80. Choose thresholds from real behavior, keep a breaker per dependency (and often per operation or region), and tell the agent what to do while it is open. Production breakers also need to handle concurrent trial calls.
Rate limits and concurrency
- Limit per tool, per user and per task, so that one runaway agent cannot consume everything.
- Limit calls in progress, not only calls per minute.
- Queue with a maximum length and reject early beyond it.
- Cache safe reads with a clear age, separated by permission.
- Batch when the service supports it, and report partial failures item by item.
Validate results
A successful status code does not mean a usable answer. Check results before the model sees them.
| Check | Catches |
|---|---|
| Schema | Missing or renamed fields |
| Meaning | Negative stock, dates in the past, wrong currency |
| Identity | A record for a different customer |
| Completeness | One page presented as everything |
| Freshness | Old cached data |
| Size | Results that would crowd out instructions |
| Effect | "Accepted" is not "done"; read back important changes |
Text inside a result, such as a web page, an email or a ticket comment, is untrusted input. It may contain instructions aimed at the model. Mark it as data, and enforce permissions so that following such instructions achieves nothing harmful. See Prompt Injection Attacks and Defenses.
Normalize and trim output
- Convert dates, money and identifiers to one convention across tools.
- Remove secrets and fields the task does not need.
- Replace large content with a reference and a short preview.
- Say plainly when something was cut: silent truncation leads to confident wrong answers.
- Keep the full response available to authorized people for diagnosis, under retention rules.
Context Assembly, Retrieval, Compression and Caching covers how results fit into the context budget.
Recover part-finished work
A task with several writes can stop halfway. Decide the recovery for each step before building it.
| Strategy | How it works | Use when |
|---|---|---|
| Resume | Continue from saved progress | Steps are safe to continue later |
| Compensate | Run an opposite action | A reservation can be released |
| Roll forward | Complete the remaining steps | Undoing is worse than finishing |
| Hand over | Give a person the exact state | Judgment is needed |
Record each intended action before attempting it and its outcome after. A person taking over needs to know what was done, what was not and what is uncertain. Stateful and Long-Running Agent Architecture shows how to persist that record.
What the model should and should not control
Let the model choose among legitimate next steps: correct an argument, search differently, ask the user or give up gracefully. Keep retry counts, delays, deadlines, keys and permission decisions in code. Limit how often the same tool may be called with the same arguments, and stop a task that makes no progress. See Agent Decisions: Confidence, Stopping, Loops and Budgets.
Declare behavior per tool
An executor can treat tools differently only if each one states how it behaves. A small policy record is enough.
| Setting | Search catalog | Create booking | Run report job |
|---|---|---|---|
| Changes state | No | Yes | Creates a job |
| Deadline | Short | Moderate | Short to start; long to finish |
| Retry | Temporary failures | Only with the same key | Only with the same key |
| On unknown outcome | Retry | Look up by key | Look up by key |
| While unavailable | Cached result with age | Queue or hand over | Tell the user to expect delay |
| Result limit | Ten items | One record | Reference to the file |
The values are examples; set them from measurements and business needs. Review them when a provider changes its limits or when traces show frequent timeouts. A deadline copied from another tool is a common source of both premature failures and long hangs.
Ordering and parallel calls
Some model interfaces can request several tool calls at once. Running independent reads together saves time. Running writes together can create races, such as two updates to the same record or a payment that should have waited for a validation. Let the executor decide: run calls in parallel only when they are marked safe to do so and do not depend on each other, preserve the link between each result and its request, and report every outcome even when some fail. When one call in a group needs approval, do not run the dependent ones in the meantime. Parallelism, Deadlocks and Conflict Resolution looks at the same problem across agents.
Measure reliability per tool
| Measure | Signals |
|---|---|
| Success rate after retries | What users experience |
| First-attempt success rate | Hidden instability |
| Error class mix | Whether to fix schemas, permissions or capacity |
| Slow-tail latency | Timeout settings |
| Unknown outcomes | Need for status checks |
| Duplicate effects | Failure of idempotency; investigate every one |
Rehearse failure
Build a test double for each important tool that can delay, return errors, return malformed data, succeed while dropping the reply and apply a request twice. Run representative tasks against it and check the real effect in the double's records, not the agent's description of it. Add each production incident as a new case.
A carrier service begins taking forty seconds to respond. The agent waits, retries and runs out of its time budget, leaving customers without any answer. The team sets a six-second deadline, adds a breaker, shows the last known status with its age and offers to send an update. Task completion recovers even though the carrier has not.
Degrade gracefully
Decide in advance what the agent says and does when a tool is unavailable. Options include answering from older data with its age shown, offering a partial result, queuing the request with a promise to follow up, or passing it to a person. Write these as explicit paths in code. Otherwise the model improvises, and improvisation under failure is where agents most often claim that something happened when it did not. Test each path by switching the dependency off, and check that the message to the user is true.
Keep a way to disable a single tool quickly without redeploying the whole agent. If a downstream system starts returning wrong data, removing the tool is usually safer than hoping the model notices. The registry in Agent Tools, Function Calling and Tool Registries is a natural place for that switch.
Common mistakes
- No timeout, or one longer than the task allows.
- Passing raw exceptions to the model.
- Retrying writes without keys.
- Retrying invalid or forbidden requests.
- Silently truncating results.
- Trusting a success code without checking content.
- Letting the model manage backoff.
Checklist
- All calls pass through one execution layer.
- Each tool declares effects, deadline and result limits.
- Failures map to a small set of classes with advice.
- Writes use idempotency keys and status checks.
- Retries are bounded, jittered and in one place.
- Breakers and rate limits protect dependencies.
- Results are validated, trimmed and labeled.
- Recovery for part-finished work is defined and tested.
Frequently asked questions
How many times should a tool be retried?
Often once or twice for temporary failures, within the task deadline. Base the number on the service's behavior and the cost of waiting.
Should the model see error messages?
It should see a safe, specific summary that helps it choose the next step. Keep technical detail in logs.
What if a service has no idempotency support?
Check for an existing result before writing, use a unique reference the service stores, or require human confirmation after an unknown outcome. Some risk of duplication may remain.
Is a circuit breaker needed for every tool?
No. Add one where a failing dependency is called often or is slow to fail. Simple, rare calls may need only timeouts.
References and further reading
- AWS Builders' Library: timeouts, retries and backoff with jitter
- AWS Builders' Library: making retries safe with idempotent APIs
- Azure Architecture Center: circuit breaker pattern
- RFC 9457: problem details for HTTP APIs
- RFC 9110: HTTP semantics
Next steps
Tool Permissions, Approvals and Abuse Risks
Control which calls may happen.
Tool Testing and Observability
Prove the behavior and watch it.
Fix Tool Calling and Invalid JSON Errors
Diagnose failing calls.