Designing an AI Agent Loop as a State Machine
Design a reliable AI agent loop with explicit states, guarded transitions, bounded execution, and recovery illustrated through a support-ticket workflow.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
An AI agent loop becomes easier to operate when its next action is constrained by explicit state. The model can propose a search, a tool call, or a final answer; application code decides whether that transition is legal, whether resources remain, and what evidence is required before declaring success.
A state machine does not make a model deterministic. It makes the boundaries around model decisions inspectable. This guide develops a hypothetical support-ticket agent to show how states, transition guards, and terminal outcomes fit together.
Separate model proposals from workflow authority
Anthropic distinguishes predefined workflows from agents whose models dynamically choose their process and tool use. It also recommends adding complexity only when simpler approaches fall short. A useful architectural interpretation is to let a model choose among permitted actions while retaining an explicit outer workflow. That interpretation is a design recommendation here, rather than a guarantee from a framework. Anthropic: Building effective agents.
For example, a support agent may decide which knowledge article to retrieve next. It should not decide that authentication is unnecessary or invent a transition that skips refund authorization. Those rules belong in application code and the downstream service.
The unit of control is a transition, not a paragraph of conversation. A proposed action should have a known type, validated arguments, and a relationship to the current task. Free-form reasoning can assist the decision, but the workflow should not parse a narrative such as “I have probably finished” as proof of completion.
Define states around observable work
A minimal design can distinguish these states:
| State | What the application knows | Permitted next outcomes |
|---|---|---|
| RECEIVED | A ticket exists, identity is unresolved | READY or ESCALATED |
| READY | Required identity and task scope are established | DECIDING |
| DECIDING | The model is choosing a permitted next action | READING, WAITING_APPROVAL, VERIFYING, or ESCALATED |
| READING | A read-only tool request is in progress | DECIDING or ESCALATED |
| WAITING_APPROVAL | A specific proposed mutation awaits authorization | ACTING, DECIDING, or CANCELLED |
| ACTING | An authorized operation has a stable action identity | VERIFYING or RECONCILING |
| VERIFYING | The application is checking the outcome | SUCCEEDED, DECIDING, or ESCALATED |
| RECONCILING | An operation may have happened, but its result is unknown | VERIFYING or ESCALATED |
SUCCEEDED, ESCALATED, and CANCELLED are terminal for this run. A new customer reply creates a new event or run according to the product’s policy; it does not silently reopen an already completed execution.
State-machine terminology predates LLM agents. The W3C SCXML specification defines explicit states, transitions, events, and final states. Its distinction between reaching a nested final state and completing the enclosing machine is useful when an agent contains subworkflows: finishing retrieval does not mean the customer’s task is complete. You do not need to adopt XML to use that distinction. W3C SCXML.
Keep business state separate from chat history
The conversation records what was said. Execution state records what is currently true. In this illustrative design, the authoritative record contains:
{
"run_id": "run_42",
"revision": 7,
"status": "DECIDING",
"ticket_id": "ticket_981",
"tenant_id": "tenant_3",
"policy_version": "returns-v6",
"evidence_ids": ["order_72@v3", "returns-v6#section-2"],
"model_steps_used": 3,
"remaining_tool_calls": 4,
"pending_action_id": null,
"deadline_at": "2026-11-10T12:00:00Z"
}
These identifiers are fictional. Production values should reference durable records rather than copying every sensitive document into the workflow database. Store the authorization scope in a server-controlled context; never accept a tenant identifier suggested by the model as authority.
A revision number supports conditional writes: commit the next transition only if the stored revision still matches the revision that the worker read. This prevents two workers from both advancing the same snapshot. It does not, by itself, prevent duplicate remote actions; the action service needs its own deduplication contract.
LangGraph provides one implementation of explicit state, nodes, and conditional edges. Its state channels use reducers to combine updates; the default is generally replacement rather than automatic accumulation. If two branches append evidence, define the merge behavior deliberately, including deduplication and provenance. The framework’s graph semantics do not replace application-level business invariants. LangGraph Graph API overview.
Put guards on transitions
For each transition, specify its trigger, guard, effect, and resulting state. Consider DECIDING to READING:
- Trigger: the model proposes
lookup_order. - Guard: arguments satisfy the tool schema; the authenticated user may access that order; the deadline and tool budget allow the call.
- Effect: persist an operation record and dispatch the read request with a correlation identifier.
- Result: enter READING and record the request identifier.
The schema check proves that an order identifier has the expected shape. Authorization proves that this user may read that order. These checks answer different questions.
For mutations, bind approval to the exact operation, arguments, target, and relevant policy version. If the proposed refund changes after approval, return to the decision or approval state. A generic “the user approved earlier” flag loses the relationship between permission and effect. The companion guide on human-in-the-loop approval gates develops this boundary further.
A hypothetical support-ticket walkthrough
Assume a customer reports a duplicate charge. The example policy permits the agent to investigate transactions and prepare a recommendation, but requires a support specialist to approve any refund.
First, RECEIVED validates the session and establishes the customer-account relationship. READY constructs a bounded context packet containing the ticket, permitted tools, and current policy references. DECIDING proposes a transaction lookup. The guard rejects any account identifier that is outside the established scope.
READING receives two transaction records. The model proposes a refund for the second record. A deterministic check compares amount, currency, transaction status, and policy eligibility. The workflow creates an immutable proposal and enters WAITING_APPROVAL. The customer receives a truthful status update: investigation is complete and a refund recommendation is awaiting review.
After an authorized specialist approves that proposal, ACTING submits the operation using the persisted action identity. If the response confirms success, VERIFYING reads the refund record and checks that its transaction and amount match the approved proposal. Only then does the run become SUCCEEDED.
Suppose the request times out instead. The workflow enters RECONCILING, queries by action identity, and determines whether the refund was committed. It does not ask the model to guess whether retrying feels safe. AWS’s discussion of retries emphasizes that a timeout does not establish that a side effect failed, and that retries can amplify overload. AWS: Timeouts, retries, and backoff with jitter.
This is where idempotency for agent actions becomes part of the loop’s correctness rather than a separate optimization.
Bound the loop with several independent limits
A maximum step count is useful, but insufficient. A single slow request can exceed the task deadline without consuming many steps. A small number of expensive requests can exhaust a budget. Repeated searches can consume steps while producing no new evidence.
Use independent limits for model decisions, tool calls, wall-clock duration, resource expenditure, and repeated failure classes. Reserve resources before dispatching work when concurrent branches share a budget. Otherwise, each branch can observe the same remaining allowance and collectively overspend it.
Define a progress signal appropriate to the task: a previously missing required field becomes known, a fresh evidence identifier is added, or an unresolved verification condition is discharged. Different wording in an answer is not progress. After repeated equivalent actions without a meaningful state change, escalate with the evidence already collected.
A framework’s recursion limit remains a useful last line of defense. LangGraph documents that reaching its step limit before a stop condition raises a recursion-limit error. Treat that as an operational outcome to handle, rather than relabeling it successful completion. LangGraph recursion-limit troubleshooting.
Validate transitions before evaluating answers
Start with invariants that can be checked without a language model:
- Every terminal outcome records a reason and the final state revision.
- No mutation executes without authorization bound to the operation.
- No tool call starts after cancellation or deadline expiry.
- Every successful mutation has a verified outcome or an explicitly documented alternative confirmation contract.
- Stale workers cannot overwrite newer workflow state.
Then exercise failure sequences: cancellation during a tool call, approval arriving after expiry, a repeated queue delivery, an invalid model action, a tool response with the wrong tenant, and a crash immediately after the remote operation commits. Inject each failure at the transition boundary and inspect both stored state and external effects.
Finally evaluate whether the agent solves the intended support task. A perfectly legal sequence can still retrieve irrelevant evidence or recommend the wrong resolution. State-machine tests verify control; task evaluations verify usefulness. Both are necessary, and neither proves the other.
Frequently asked questions
Does a state machine eliminate agent autonomy?
No. It defines where model choices are allowed and which choices require independent checks. An agent can choose its next investigation step within a bounded state while application code enforces authority and resource limits.
Should every tool call become its own state?
Use a separate state when the operation has meaningful waiting, recovery, or authorization behavior. For short, pure computations, a function inside a node may be sufficient. Excessively fine states add storage and operational complexity without improving recovery.
Can chat messages be the entire state?
They can support a small demonstration. For a workflow with approvals, retries, and remote mutations, explicit fields make invariants and recovery easier to inspect. Keep messages as evidence and interaction history; maintain execution truth in validated records.
Sources and scope
The cited documents establish state-machine concepts, graph execution mechanics, agent design patterns, and distributed-call failure behavior. The support workflow, field names, and transition policy are an illustrative architecture developed here; they are not a benchmark or a tested reference implementation. Adapt the guards and success criteria to the actual permissions and outcome contracts of your service.
Source reference list
Related reading
- Human-in-the-Loop Agents: Designing Useful Approval Gates
Design human-in-the-loop agent approvals with immutable proposals, qualified reviewers, expiry, durable resumption, and checks against changed resource state.
- Idempotency for AI Agent Actions: Preventing Duplicate Side Effects
Prevent duplicate AI agent actions with stable intent identities, immutable request fingerprints, durable ledgers, and recovery for uncertain outcomes.
- Durable AI Agent Workflows: Checkpoints, Replay, and Recovery
Design durable AI agent workflows with checkpoints, recorded decisions, safe retries, and recovery paths that handle crashes without duplicating actions.