Agent loops, state and human oversight
medium 7 minA loop turns a model proposal into an observed change in state.
Video lesson · Chapter 1 of 4
A parcel with two calls left
Theory
Read or listen first. About 3 min.
What it is
A loop turns a model proposal into an observed change in state. The controller owns the run identity, limits and stop rule. Tools return evidence or explicit errors. Human approval can intervene before a consequential step.
Why it exists
Compare the proposed action, the actual external outcome and the state used for the next turn. This detects loops that claim success without an effect, repeatedly consult the same evidence or resume from an obsolete checkpoint.
Stop after the parcel is located
Inside this chapter
Chapter sources- The Canonical Agent Loop
- A loop reads current state, chooses a bounded action, executes it through the host and records the observation. Stop on a verified result, a human handoff, a deadline or an exhausted budget. A model declaring success is not sufficient if the external operation never completed.
Each pass through the loop should change something you can check: a new observation, a narrowed set of options or a completed effect. The stop check runs after every observation and compares state against the goal, not against the model's confidence. A common failure is a loop that ends because the model wrote "done" while the tool call it relied on timed out; the controller must record that as unverified.
Example. The agent has found order 42 and has one call left. Stop on verified goal completion rather than spending the remaining allowance.
Another example. A coding agent loops edit, run tests, read failures. It should stop when the target test passes and the rest stay green, not when it has written a confident commit message.
One turn of the loop for order 42 - 1Read stategoal, observations, 2 calls left
- 2Choose bounded actionlookup_shipment(42)
- 3Execute via hostgateway checks ownership
- 4Record observationorder 42 at depot B
- 5Check stop ruleverified answer: finish
Repeat: back to Read stateThe loop exits on a verified result, a handoff, a deadline or an exhausted budget. Unused budget is not a reason to keep going.
- Core Components of an Agent
- Separate the model, state store, tool gateway and controller. The controller owns scheduling and termination, the gateway owns authorization and execution, and the store records observations. This separation lets an engineer replay an unsuccessful lookup without replaying a real write.
Separation of duties is what makes the system testable. The controller owns the loop and the stop rule, the gateway owns permission and execution, and the store keeps the record. Because the model only ever proposes, you can replay a failed run with recorded observations and a stubbed gateway, inspecting each decision without sending a real email or moving real money.
Example. Replace a real tool with a deterministic fixture and replay the same controller. The recorded decision and observation can now be tested separately.
Four parts with separate jobs
Swap the real tool for a fixture behind the gateway and the controller cannot tell the difference, which is what makes replay safe. - Stateless vs Stateful Agents
- A stateless call receives everything it needs in the request. A stateful application can recover history from a durable run ID. Storing a transcript alone may miss pending actions and approval status. Persist the fields required to resume safely after the process restarts.
A stateless call works because the caller sends the full context every time. Once a run can pause (for approval, for a slow tool, for a deploy) you need a durable record keyed by run ID that holds more than chat history: the pending operation with its exact arguments, its approval status, its owner and an operation key. Test it by killing the worker mid-pause and checking the replacement resumes without asking the model to reconstruct the pending action from prose.
Example. Restart a worker after it asks for approval. A durable record should show which operation is pending, its exact amount and its owner.
JSON{ "run_id": "run-7f3", "status": "awaiting_approval", "owner": "customer-118", "pending_action": { "tool": "issue_refund", "order_id": "42", "amount": "24.00", "currency": "USD", "operation_key": "run-7f3/step-4" }, "approval": { "requested_at": "2026-03-02T10:15:00Z", "decided": false }}A durable run record a restarted worker can resume from. A transcript alone would not say which write is pending or whether it was approved. - Agent Control Flows
- Linear, conditional, looping and parallel control flows carry different failure modes. A parallel branch may finish after its sibling has changed shared state. Define how updates merge, whether late results remain eligible and who decides that the run is complete.
Parallel branches are where most surprises live. If branch A sets the hotel and branch B, finishing later, writes the whole itinerary object back, A's work vanishes. Decide per field whether updates append, replace or raise a conflict, and whether a result that arrives after the run is marked complete is still allowed to apply.
Example. Let two branches update the same itinerary. Decide whether their updates append, replace or conflict before executing them in parallel.
Control shapes and how each one breaks
Shape Example Typical failure Rule to define Linear lookup then answer step fails silently what each step must return Conditional billing or shipping branch wrong branch taken allowed destinations, fallback Loop search until enough evidence never terminates budget and progress check Parallel two branches edit one itinerary late result overwrites newer state merge rule: append, replace or conflict - Simple Task Agents
- A simple task agent works best with a narrow goal, a small toolset and an explicit terminal result. For a delivery lookup, one authorized query can be enough. Limit free-form exploration and test malformed IDs, missing orders and empty search results.
A small toolset is a safety feature and a quality feature at the same time. The model has fewer ways to be wrong, and you can enumerate the edge cases in a short test file. Out-of-scope requests should produce a polite handoff, not an improvised attempt with whatever tools happen to be loaded.
Example. A one-task order assistant receives a request to purchase a new item. It should stay within its declared scope or hand off.
Another example. An invoice-status bot with one
get_invoicetool should reply to "change my billing address" with a link to the account page, not by searching for an update tool.Narrow order assistant
- One goal: report delivery status
- Tools:
lookup_orderonly - Terminal result: status, or a handoff
- Tested on malformed IDs, missing orders, empty results
Free-form explorer
- Accepts "buy me a new one" and tries
- Has purchase tools it never needed
- No clear terminal result
- Untested paths grow with every tool added
- Autonomous Looped Agents
- A looped agent can pursue intermediate goals across several turns. Bound steps, time, spend and repeated actions independently. Detect repeated observations without progress and hand off. Reaching a numerical step limit is an operational stop, not evidence that the task was solved.
Bound steps, wall-clock time, spend and repeated actions separately, because each catches a different failure. A progress check compares the latest observation with recent ones; four identical lookup results in a row is a stuck loop even if time remains. Report a limit-triggered stop as exactly that, so dashboards do not count it as success.
Example. The same read-only lookup returns the same record four times. A progress check should stop the run even when the clock budget remains.
Run states with independent stop signals
BudgetStop is an operational outcome. Only Done means the task was solved. - Human-in-the-Loop Agents
- Human review belongs at a meaningful decision boundary. Show the specific proposed write, affected entity and consequence. Bind approval to those arguments and expire it when relevant state changes. The application needs a cancel or deny path that completes cleanly without performing the operation.
Put review where a mistake becomes expensive or visible to others, and show the reviewer the concrete write rather than the model's summary of it. Store the approval alongside the exact arguments it covered and invalidate it when they change or when relevant state moves on. Make deny and cancel first-class paths that finish the run cleanly; otherwise reviewers learn that the only way to stop a bad action is to approve and then clean up.
Example. Review a proposed calendar invitation, then change its recipient. Approval for the earlier recipient should not authorize the revised invitation.
Another example. A support agent drafts a goodwill credit of 15 GBP. The reviewer approves; the agent then raises it to 50 GBP after reading more history. The host must ask again.
Approval bound to exact arguments
The approval is stored with a hash of the arguments. Any change voids it, and denial is a clean, completed outcome. - Cancellation during an action
- Treat step limit, wall-clock deadline and cancellation as separate stop signals. If a pending external call may already have taken effect, reconcile it through the durable business record before producing the terminal outcome.
Step limit, deadline and user cancellation are different signals and should be recorded as such. The dangerous moment is when a call is in flight: the remote side may have committed even though you never saw the reply. Before writing a terminal outcome, query the system of record by operation key and report what actually exists, then follow that service's own cancellation rules.
Example. The user cancels after the warehouse accepts a reservation but before its response reaches the worker. Report the recorded hold and use the service’s cancellation policy.
Cancel arrives while the reservation is in flight
The worker reconciles through the warehouse record before reporting. Saying nothing happened would be wrong.
How it works
Step through the idea, or press Play.
Run state. Order 42 · 2 calls left
Understand it
Worked example
Stop after the parcel is located
- 1
Order 42 · 2 calls left
The host records the user goal, current observations and remaining budget. The model proposes an allowed read.
- 2
Order 42 is at depot B
The gateway checks ownership and returns a typed result. The observation is added to state with its source and timestamp.
- 3
Verified location · finish
The goal has a verifiable answer. A second identical lookup adds cost without new evidence, even though one budgeted call remains.
Bound the run’s external work
Follow the handoffs
Budget and evidence turn by turn
| Turn | Action | Observation | Calls left | Controller decision |
|---|---|---|---|---|
| 0 | none | goal: locate order 42 | 2 | ask model for an action |
| 1 | lookup_shipment(42) | at depot B, scanned 09:10 | 1 | goal verified: finish |
| (not run) | lookup_shipment(42) again | would repeat the same record | 1 | skipped: no new evidence |
Summary
The whole topic in one minute.
No observation supports the reported delivery. A timeout is a failed lookup, not evidence that a shipment reached its destination.
Compare the proposed action, the actual external outcome and the state used for the next turn. This detects loops that claim success without an effect, repeatedly consult the same evidence or resume from an obsolete checkpoint.