Agent State, Memory and Reliability
Reliable agents are built around the model, not inside it. The model proposes the next action; a runner written in ordinary code keeps the state of the task, checks every tool call against a typed contract, retries failures that are safe to retry, prevents duplicate side effects, enforces a step budget, asks a person to approve risky actions, and records a trace of everything. With these, a mistaken or manipulated model can only do bounded, visible, reversible things.
"The Agent Loop" and "Controlling Agent Autonomy" introduced agents. This lesson builds the reliability layer.
The Building Blocks
| Block | Description |
|---|---|
| Explicit state | It is used to track the task's status, step count and results in code, not only in the prompt |
| Memory policy | What the agent may remember, for how long, and how it is corrected; short-term context vs stored memory |
| Tool contracts | It is used to define each tool's arguments and types, and reject calls that don't match |
| Retries and timeouts | Retry only failures that are safe to repeat, a limited number of times |
| Idempotency | It is used to make repeating an action harmless, for example with a unique key per message |
| Step budget | A hard limit on steps, time or cost, so a loop can't run forever |
| Human approval | It is used for irreversible, financial, external or sensitive actions |
| Trace | A record of every proposed action, its arguments and result, for debugging and audit |
Example: A Reliable Runner
This runner executes a plan for "remind the family of S007 about the lab fee". The plan's steps are written by hand for this lesson to stand for what a model might propose, including two bad steps; the runner's checks are the real point. The fee service is made to time out once, as real services do.
import json
# ---- Tools, each with a typed contract -------------------------------------------------
FEES = {"S007": {"fee": "lab", "amount": 45, "due": "2026-09-30", "paid": False}}
SENT = set() # idempotency: message keys already sent
calls = {"lookup_fee": 0}
def lookup_fee(student_id: str) -> dict:
calls["lookup_fee"] += 1
if calls["lookup_fee"] == 1:
raise TimeoutError("fee service did not answer in 2 s") # a flaky dependency, the first time
return FEES[student_id]
def draft_reminder(student_id: str, amount: int, due: str) -> str:
return f"Reminder: the ${amount} fee for {student_id} is due on {due}."
def send_message(student_id: str, text: str, key: str) -> str:
if key in SENT:
return "already sent (duplicate request ignored)"
SENT.add(key)
return "sent"
TOOLS = { # name -> (function, argument types, needs human approval)
"lookup_fee": (lookup_fee, {"student_id": str}, False),
"draft_reminder": (draft_reminder, {"student_id": str, "amount": int, "due": str}, False),
"send_message": (send_message, {"student_id": str, "text": str, "key": str}, True),
}
# ---- The runner: explicit state, validation, retries, approval, budget, trace ------------
def run(plan, approve, max_steps=6, retries=2):
state = {"status": "running", "step": 0, "memory": {}}
trace = []
for action in plan:
if state["step"] >= max_steps:
state["status"] = "stopped: step budget reached"
break
state["step"] += 1
name, args = action["tool"], dict(action["args"])
args = {k: state["memory"].get(v[1:], v) if isinstance(v, str) and v.startswith("$") else v for k, v in args.items()}
if name not in TOOLS:
trace.append((state["step"], name, "REJECTED: not an allowed tool"))
continue
fn, types, needs_approval = TOOLS[name]
bad = [k for k, t in types.items() if not isinstance(args.get(k), t)] + [k for k in args if k not in types]
if bad:
trace.append((state["step"], name, f"REJECTED: invalid arguments {bad}"))
continue
if needs_approval and not approve(name, args):
trace.append((state["step"], name, "WAITING: needs a person to approve"))
state["status"] = "paused for approval"
break
for attempt in range(1, retries + 2):
try:
result = fn(**args)
break
except TimeoutError as e:
trace.append((state["step"], name, f"attempt {attempt} failed: {e}; retrying"))
else:
state["status"] = "failed"
break
state["memory"][action.get("save_as", name)] = result
trace.append((state["step"], name, f"ok -> {json.dumps(result)[:60]}"))
else:
state["status"] = "done"
return state, trace
# The steps a model might propose for "remind the family of S007 about the lab fee". They are written
# by hand for this lesson, including two bad ones, to show what the runner does with each.
plan = [
{"tool": "lookup_fee", "args": {"student_id": "S007"}, "save_as": "fee"},
{"tool": "draft_reminder", "args": {"student_id": "S007", "amount": "45 dollars", "due": "2026-09-30"}},
{"tool": "draft_reminder", "args": {"student_id": "S007", "amount": 45, "due": "2026-09-30"}, "save_as": "text"},
{"tool": "issue_refund", "args": {"student_id": "S007", "amount": 45}},
{"tool": "send_message", "args": {"student_id": "S007", "text": "$text", "key": "S007-lab-2026-09"}},
{"tool": "send_message", "args": {"student_id": "S007", "text": "$text", "key": "S007-lab-2026-09"}},
]
for label, approve in [("No approval given", lambda n, a: False), ("A staff member approves", lambda n, a: True)]:
calls["lookup_fee"] = 0
state, trace = run(plan, approve)
print(f"{label}: status = {state['status']}, steps used = {state['step']}")
for step, name, what in trace:
print(f" {step}. {name:15} {what}")
print()No approval given: status = paused for approval, steps used = 5
1. lookup_fee attempt 1 failed: fee service did not answer in 2 s; retrying
1. lookup_fee ok -> {"fee": "lab", "amount": 45, "due": "2026-09-30", "paid": fa
2. draft_reminder REJECTED: invalid arguments ['amount']
3. draft_reminder ok -> "Reminder: the $45 fee for S007 is due on 2026-09-30."
4. issue_refund REJECTED: not an allowed tool
5. send_message WAITING: needs a person to approve
A staff member approves: status = done, steps used = 6
1. lookup_fee attempt 1 failed: fee service did not answer in 2 s; retrying
1. lookup_fee ok -> {"fee": "lab", "amount": 45, "due": "2026-09-30", "paid": fa
2. draft_reminder REJECTED: invalid arguments ['amount']
3. draft_reminder ok -> "Reminder: the $45 fee for S007 is due on 2026-09-30."
4. issue_refund REJECTED: not an allowed tool
5. send_message ok -> "sent"
6. send_message ok -> "already sent (duplicate request ignored)"Explanation:
| Step | What happened | Which block |
|---|---|---|
| 1 | The fee service timed out, was retried, then answered | Retries (a lookup is safe to repeat) |
| 2 | amount: "45 dollars" was rejected: the contract says an integer | Tool contracts |
| 3 | The corrected draft succeeded and was saved in state as text | Explicit state |
| 4 | issue_refund was rejected: it isn't in the tool list | Least privilege |
| 5 | Sending a message waited for a person; without approval the task paused | Human approval |
| 6 | With approval, a second identical send was ignored: same key | Idempotency |
$textin the plan refers to a value in the runner's state, so the model doesn't have to copy results around (and can't quietly change them).- The step budget (6) stops runaway loops; the trace records every attempt, including failures, so a person can see exactly what happened.
- Retries are only for safe actions. Retrying a lookup is harmless; retrying a payment could charge twice, which is why sends and payments need idempotency keys.
Orchestration Patterns
| Pattern | How it works | Good for |
|---|---|---|
| Sequential | Fixed steps, one after another | Predictable tasks; often a workflow, not an agent |
| Parallel | Independent steps at the same time, then combined | Searching several sources at once |
| Supervisor | One agent plans and hands sub-tasks to workers | Larger tasks with clear parts |
| Handoff | An agent passes the conversation to a specialist | Support desks with different topics |
| State machine | Allowed transitions between named states | Approvals, payments, anything with rules |
More agents mean more coordination, more cost and more ways to fail; see "Multi-Agent Systems". When a fixed workflow can do the job, use it: see "Workflows vs Agents".
Common Mistakes
Letting the model hold all the state. Prompts get long, and values change silently; keep state in code.
Retrying everything. Retrying a non-idempotent action can send or charge twice.
No step or cost limit. A confused agent can loop for hours.
No trace. Without one, you can't explain or fix what the agent did.
Interview Corner
How do you make a tool-using agent reliable?
Keep explicit state in code, validate every tool call against a typed contract, retry only safe actions with limits and timeouts, use idempotency keys for side effects, enforce step and cost budgets, require approval for risky actions, and trace every step.
What is idempotency, and why does it matter for agents?
An action is idempotent if doing it twice has the same effect as doing it once. Agents and networks repeat requests, so sends, bookings and payments need a unique key that makes duplicates harmless.
Practice
Exercise: a budget test. Set max_steps=3 and run both cases again. Where does each stop, and what status does it report? Then make the fee service fail three times in a row: what happens?
Check your understanding:
- Why was step 2 rejected?
- Why is retrying
lookup_feesafe but retrying a payment risky? - What stopped the duplicate message?
Key Takeaways
Quick reference
| Need | Practice |
|---|---|
| Validate tool calls | Typed argument contracts; reject extras |
| Survive flaky services | Limited retries with timeouts, only for safe actions |
| Avoid duplicates | Idempotency keys for sends, bookings and payments |
| Stop loops | Step, time and cost budgets |
| Risky actions | Human approval, with the details shown |
| Explain behavior | A trace of every step |
Was this tutorial helpful?