The short answer: every agent loop needs explicit limits on time, turns, and retries, plus a clear path to human review when those limits are hit or when a high-impact action is about to occur. Retries should be narrow and observable. Timeouts should be enforced on both the model call and the overall agent run. Human review should be a first-class exit, not an afterthought.
I used to treat agent failures as rare events that could be fixed by “just one more retry.” That habit produced long, expensive loops and occasional silent wrong answers. The version that survived in my own tooling is stricter: bounded retries, hard timeouts, and an immediate escalation path when the agent cannot finish cleanly. This article is the recovery pattern I now install before the agent ever sees production traffic.
What This Solves
You have a small agent (or are about to ship one) and you need it to fail safely. By the end of this post you will know:
Which failure modes are worth automatic retry and which are not
How to enforce turn limits and wall-clock timeouts
Where to insert human review without destroying the value of automation
A practical recovery ladder that stays observable
This belongs in Agents and Automation. It assumes you already have a minimal agent that uses one or a few verified tools.
Who Should Use This Approach
Developers who have built at least a small agent loop and have watched it encounter real errors, timeouts, or ambiguous tool results. If you are still deciding whether you need an agent at all, start with the earlier “Do You Need an Agent?” article. Recovery is cheaper when the agent itself is already small.
The Recovery Ladder
Handle problems in this order:
Detect – classify the failure from status, exception, finish_reason, or tool-result content
Retry narrowly – only the step that failed, with a clear budget
Fall back – a safer deterministic path or a cached/default answer when appropriate
Escalate to human review – when the stakes are high or the budget is exhausted
Stop – never let the agent run indefinitely
Most of the damage from agents comes from skipping steps 3–5 and simply looping.

Failure Classes and What to Do
Transport / timeout errors
The model call or the tool call never completed.
Action: retry the individual call a small number of times (usually 1–2) with backoff. If the overall agent wall-clock limit is reached, stop and escalate.
Authentication or configuration errors
Missing key, wrong base URL, invalid model name.
Action: do not retry. These will not fix themselves. Fail fast and alert.
Rate limits (429)
Action: honor Retry-After when present, otherwise use a short exponential backoff. Count these against the overall turn or time budget so a rate-limit storm cannot keep the agent alive forever.
Invalid tool arguments
The model requested a tool with unusable arguments.
Action: return a clear error as the tool result (as described in the earlier invalid-arguments article) and let the model try once more. Do not execute.
Tool execution failures
The real function raised an exception or returned an error.
Action: return the error as the tool result. Decide in advance whether the agent is allowed another turn or must escalate.
Model never produces a final answer
The agent keeps requesting tools or producing empty content until the turn limit.
Action: stop at the limit and escalate or return a safe fallback.
High-impact side effects
The next tool call would send an email, charge a card, delete data, or change production state.
Action: require human approval before execution, regardless of how confident the model appears.
Concrete Limits to Install
text
MAX_MODEL_TURNS = 4–6 # hard stop
MAX_TOOL_RETRIES = 1–2 # per tool call
PER_CALL_TIMEOUT_SEC = 30–60 # individual model or tool call
AGENT_WALL_CLOCK_SEC = 120–300 # entire runThese numbers are starting points, not universal constants. The important property is that they exist and are enforced in code, not only in documentation.
Minimal Recovery Skeleton
Python
import time
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
timeout=45.0, # per-call timeout
)
MAX_TURNS = 5
AGENT_DEADLINE = 180 # seconds
def run_agent_with_recovery(user_question: str) -> dict:
"""
Returns a structured result:
{
"status": "success" | "fallback" | "needs_human" | "failed",
"answer": str | None,
"reason": str,
"turns_used": int,
}
"""
start = time.monotonic()
messages = [
{
"role": "system",
"content": "You are a precise assistant with one tool. Finish as soon as you can answer.",
},
{"role": "user", "content": user_question},
]
for turn in range(1, MAX_TURNS + 1):
if time.monotonic() - start > AGENT_DEADLINE:
return {
"status": "needs_human",
"answer": None,
"reason": "agent_wall_clock_exceeded",
"turns_used": turn - 1,
}
try:
completion = client.chat.completions.create(
model="grok-4-1-fast-reasoning",
messages=messages,
tools=TOOLS, # defined elsewhere
tool_choice="auto",
)
except Exception as e:
# Narrow retry budget for transport errors could go here
return {
"status": "failed",
"answer": None,
"reason": f"model_call_failed: {type(e).__name__}: {e}",
"turns_used": turn,
}
choice = completion.choices[0]
print(f"turn={turn} finish_reason={choice.finish_reason} usage={completion.usage}")
if not choice.message.tool_calls:
return {
"status": "success",
"answer": choice.message.content or "",
"reason": "final_answer",
"turns_used": turn,
}
# Tool-call path (validation + execution omitted for brevity;
# use the patterns from earlier articles)
messages.append(choice.message)
for tc in choice.message.tool_calls:
result = handle_tool_call_safely(tc) # must never raise
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"content": result,
}
)
return {
"status": "needs_human",
"answer": None,
"reason": "max_turns_exceeded",
"turns_used": MAX_TURNS,
}The caller now receives a structured outcome instead of an unbounded string. That structure is what makes human review and metrics possible.
Where Human Review Belongs
Insert a human checkpoint when:
The agent hits a turn or time limit
A tool result indicates high uncertainty or partial failure
The next action is irreversible or high-cost
The user’s question itself is flagged as sensitive
The review interface can be as simple as a queue that stores the full message list, the tool results, and the reason for escalation. The human should see the same evidence the logs contain—no more, no less.
What Not to Retry
Authentication failures
Permanent validation errors the model has already been told about
Business-rule rejections that will not change on a second attempt
Any step whose side effects are not idempotent unless you have explicit compensating logic
Retrying the wrong class of error multiplies cost and can amplify damage.
Logging for Recovery
Every agent run should produce a single structured summary:
Final status (success, fallback, needs_human, failed)
Turns used and wall-clock duration
Which tools were requested and whether they executed
The reason for any early exit
Model and usage totals
That summary is what you will query later when you decide whether the agent is worth keeping.
A Note from the Home Lab
My small status agent originally retried every failure three times and had no wall-clock limit. One night a downstream service hung; the agent kept the process alive for twenty minutes and produced a partial answer that looked complete. Adding an explicit deadline and a needs_human status turned the same incident into a clean escalation with a full trace. The agent became trustworthy precisely because it was willing to stop and ask for help.

Practical Checklist
Hard maximum on model turns exists and is enforced
Wall-clock deadline for the entire agent run exists and is enforced
Per-call timeouts are set on the client
Retries are limited and apply only to appropriate error classes
High-impact actions require human approval before execution
Every run returns a structured status, not only a text answer
Logs capture the reason for any retry, fallback, or escalation
When a Simpler Approach Is Better
If the task can be solved with a single model call or a deterministic tool round-trip, you do not need this recovery machinery. The complexity of retries, deadlines, and human queues is justified only when the agent itself is justified. When in doubt, remove the loop first.
Closing
A reliable agent is defined less by how cleverly it continues than by how cleanly it stops. Set turn limits, set time limits, retry only what is safe to retry, and give the system a first-class way to hand control back to a human.
Failure is normal. Unbounded failure is a design error.
Build the limits first.
Explain every exit path the agent can take.
Verify that a deliberate timeout, a bad tool argument, and a max-turn condition all produce a controlled, observable stop.
Build it. Explain it. Verify it.
Next we will look at what a useful Grok integration test should actually check—so you can catch these failure modes before they reach production.
Comments
No comments yet — be the first to share a thought.