Agents as State Machines
Model an agent workflow as a state machine, so that you can predict which step runs next, cap how often a loop repeats and resume after a failure.
Contentsand lesson path
On this page
- The Fragility of Unstructured Loops
- Formalizing Agents as State Graphs
- Verify Your Understanding
- Apply it
- Review Prompt
Lessons of Stateful Agent Graphs
- Agents as State Machines Concept · 15 min
- State, Nodes and Reducers Worked example · 20 min
- Lab: Routing, Cycles and Parallel Branches Lab · 25 min
- Checkpoints, Threads and Replay Lab · 25 min
- Graph Framework, Agent SDK or Plain Code? Concept · 15 min
- Check: Trace a Graph Execution Knowledge check · 8 questions
What you will learn
- Define a typed shared state and nodes that read and update it, with reducers for fields that several nodes write.
- Explain when a graph framework (for example LangGraph) adds value over a hand-written loop or a vendor agent SDK, and when it adds needless complexity.
Prerequisites: Agent Loops & ReAct
01. The Fragility of Unstructured Loops
A basic autonomous agent is often implemented as a simple while-loop: query an LLM, inspect tool calls, execute actions, append results to an in-memory message list, and repeat until no tools are requested. In toy demonstrations, this pattern functions adequately. In production, with long multi-step workflows, an unstructured while-loop starts to fail in ways that are hard to see and hard to recover from.
Because the control flow is entirely implicit and dictated by stochastic token sampling at each turn, agents can loop without end, skip mandatory authorisation checks, forget intermediate values, or lose all progress when the process crashes or restarts. Explicit state machines make that control flow visible in code, where you can bound it, test it and save it.
02. Formalizing Agents as State Graphs
A state machine is a model with a fixed set of states, a start state, rules that say which state may follow which (the transitions), and end states that the machine does not leave once it gets there. A traffic light is a simple example: it can only go from green to amber, never from green straight to red. Unlike a traffic light, the state of an agent also carries data, such as messages and counters, not just the name of the step it is in. An agent built as a state graph follows the same idea. Each node is one step of work, and the edges say which step may run next, based on the current state.
A state graph has three parts:
- The state schema: a typed record of everything the run has gathered so far, such as the conversation, intermediate results and counters.
- Nodes: functions that take the current state, do one focused job (call a model, query a database, run a script) and return only the fields they changed.
- Edges: rules that decide which node runs next. A fixed edge always goes from node A to node B. A conditional edge reads the state and picks the next node, or ends the run.
To see where state graphs help, compare three workflow shapes:
- Linear pipelines (chains). Step A feeds step B, which feeds step C. A chain is simple and easy to predict, and many workflows need nothing more. It cannot go back, though: if step B fails or returns too little, a plain chain has no built-in way to retry B with the error as feedback, or to choose another path.
- Directed acyclic graphs (DAGs). DAG-based orchestrators such as Apache Airflow and Kubeflow Pipelines support parallel fan-out and branching, but a DAG by definition has no cycles. (Not every orchestrator is DAG-based: Prefect flows are plain Python and can loop.) Loops are common in agents: retry after a failed check, refine a search query, wait for a person to approve. A DAG engine cannot express such a loop without starting a new run.
- Cyclic state graphs. Graph engines for agents, such as LangGraph, allow cycles. They stop a runaway loop only with a recursion limit (10,007 super-steps by default in LangGraph 1.1.4 and later), so the exit condition is yours to write; with a checkpointer they also save the state after every step. Because each iteration is a visible graph transition rather than a hidden loop, an agent can retry and correct itself while every step stays traceable.
import operator
from typing import Annotated, List, Literal, TypedDict, get_type_hints
MAX_ITERATIONS = 3
class AgentState(TypedDict):
thread_id: str
iteration_count: int
messages: Annotated[List[str], operator.add] # reducer: append, never prune
confidence_score: float
def retrieve(state: AgentState) -> dict: # a node returns a partial update
n = state["iteration_count"] + 1 # the loop guard depends on this
return {"iteration_count": n, "messages": [f"retrieved batch {n}"],
"confidence_score": [0.4, 0.6, 0.8][n - 1]}
def route_next_step(state: AgentState) -> Literal["synthesize", "escalate",
"retrieve"]:
if state["confidence_score"] >= 0.85:
return "synthesize"
if state["iteration_count"] >= MAX_ITERATIONS:
return "escalate"
return "retrieve" # names match the nodes wired to the conditional edge
def apply_update(state: dict, update: dict) -> dict:
"""What a graph runtime does: use a field's reducer if it has one."""
hints = get_type_hints(AgentState, include_extras=True)
out = dict(state)
for key, value in update.items():
reducer = getattr(hints[key], "__metadata__", [None])[0]
out[key] = reducer(out[key], value) if reducer else value
return out
if __name__ == "__main__":
state = AgentState(thread_id="t-1", iteration_count=0, messages=[],
confidence_score=0.0)
step = "retrieve"
while step == "retrieve":
state = apply_update(state, retrieve(state))
step = route_next_step(state)
print(f"iteration {state['iteration_count']}: "
f"confidence {state['confidence_score']} -> {step}")
print("messages:", state["messages"])
bad = apply_update(state, {"confidence_score": "high"}) # no error here...
print("TypedDict accepted:", repr(bad["confidence_score"]))
try:
route_next_step(bad)
except TypeError as exc: # ...it fails later, in another node
print("router failed:", exc)The apply_update and while loop play the part of the graph runtime, so the example runs with the standard library (Python 3.12 or later): python3 state_machine.py. In LangGraph you would add retrieve as a node and wire route_next_step with add_conditional_edges; the node and router code stay the same.
iteration 1: confidence 0.4 -> retrieve
iteration 2: confidence 0.6 -> retrieve
iteration 3: confidence 0.8 -> escalate
messages: ['retrieved batch 1', 'retrieved batch 2', 'retrieved batch 3']
TypedDict accepted: 'high'
router failed: '>=' not supported between instances of 'str' and 'float'A common danger in stateful agent systems is state drift: the gradual corruption or unbounded growth of working memory over many steps. When raw chat histories are passed unpruned across dozens of graph transitions, the model uses the context less well, token costs rise and errors compound.
Explicit state makes drift visible and controllable. Each node returns a partial update instead of mutating a shared object, and a reducer decides how each field merges. Reducers do exactly what they are written to do: the operator.add reducer in the example above only appends, so messages grows without bound. Pruning happens only if you write it, for example a reducer that keeps the last N items or a summarise node. Types are not enforced either: a TypedDict state schema is a type hint, so a node can write the string "high" into confidence_score and nothing stops it until a later node fails, as the example shows. A Pydantic state model does not fix this on its own: LangGraph's documentation says run-time validation of a Pydantic state happens only on the input to the first node, not on later nodes or outputs. To reject a bad value written by a later node, validate the node's update yourself, for example with Model.model_validate on the update before returning it, or with a reducer that checks types.
03. Verify Your Understanding
04. Apply it
Turn a while-loop agent of your own into a state graph, and use these checks as you go:
- Write the state schema first, as a
TypedDictor a Pydantic model, with a reducer on every field that collects items. The types are not checked at run time, so validate updates where a bad value would do harm. - Keep side effects, such as database writes, payments and emails, in nodes of their own. You can then replay the reasoning nodes freely and give the few effectful nodes an idempotency key, so that a replay does not repeat the effect.
- Keep an iteration counter in the state, check it in the router, and keep the recursion limit as a backstop. Do not leave it to the model to decide when a failed search has been retried often enough.
- Add a
statusfield, for example"IN_PROGRESS","WAITING_HUMAN","FAILED"or"COMPLETED", so that a dashboard can show progress without reading transcripts. - Keep run data out of global variables. A node that reads only its state can run again safely when a run resumes from a checkpoint after a crash.
- Log which keys each node changed, with its latency and token use, so that you can see what each step did.
- When the counter runs out or a tool keeps failing, route to a node that writes a clear "could not finish" answer instead of letting the process crash.
05. Review Prompt
Without looking back, contrast a naive while-loop agent with a stateful agent graph. Explain how state schemas, nodes, conditional edges and reducers help you see state drift, bound execution cycles and recover after a failure, and where each one stops short (for example, a TypedDict schema is not checked at run time). Describe the role of an iteration counter as a guard, and explain why separating pure reasoning nodes from effectful nodes matters when you replay a run.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.