Make the agent's possible next steps explicit
A state graph represents an agent as explicit steps and conditional transitions. It combines flexible model decisions with deterministic control that developers can inspect and test.
What You Will Learn
- Represent an agent workflow with typed state, nodes, edges, and END.
- Separate deterministic nodes from model-directed decisions.
- Use bounded loops and parallel branches deliberately.
- Explain why explicit transitions improve testing and debugging.
A graph turns invisible control flow into testable structure
State is the structured record carried between nodes: inputs, evidence, counters, decisions, status, and errors. A deterministic node performs known logic such as schema validation. A model-directed node chooses among permitted routes. Edges define which transition may occur next, and END is an explicit finished state.
Loops should state what progress means and how many repeats are allowed. Parallel branches are useful only when subtasks are independent enough to run together and their results can be merged deterministically. Persistence and resuming a graph belong to the durable-agent lesson that follows.
Elements of an agent state graph
Move between states through checked transitions
Define typed state containing inputs, intermediate results, status, counters, and the information each node may update.
Create nodes for deterministic work, model-directed decisions, tools, validation, and human review; connect them with named edges.
Add conditional routing, bounded loops, parallel branches, and explicit stop rules only where the task needs them.
Use patterns such as orchestrator-worker for parallel subtasks and evaluator-optimizer for bounded revision.
Inspect and test every state transition; add persistence and resume behavior in the durable-agent layer when the workflow must survive interruption.
Instructional figure
An explicit agent state graph
How do typed state and named routes make an agent workflow testable?
Instructional figure
Two reusable graph patterns
When does work fan out, and when does one result loop through evaluation?
Orchestrator → parallel workers → join
Generate → evaluate → bounded revision
A Realistic Example: A research workflow
The planner chooses questions, search gathers sources, a validator checks coverage, and the graph either requests more evidence or sends the draft to final review.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
graph.add_edge("plan", "search")
graph.add_conditional_edges(
"validate", route,
{"enough": "write", "more": "search", "stop": END}
)Hands-On Runnable Python Lab: Block Execution Until the Approval Guard Passes
A refund workflow can follow START → VALIDATE → WAIT_APPROVAL → EXECUTE → END. A reviewer may also reject it, taking WAIT_APPROVAL → END without a write.
- Attempt VALIDATE → EXECUTE. There is no edge, so the runtime rejects it.
- Enter WAIT_APPROVAL and try the legal execution edge without approval. The guard rejects it.
- Set approved=True to represent a trusted reviewer event, then execute and finish.
- Inspect the trace: rejected attempts do not change the current state.
The approval edge is guarded; the shortcut does not exist
Follow solid arrows for allowed transitions. The dashed red path is a prohibited shortcut, not an executable edge. Rejection can finish without a write.
edges = {
"START": {"VALIDATE"},
"VALIDATE": {"WAIT_APPROVAL"},
"WAIT_APPROVAL": {"EXECUTE", "END"},
"EXECUTE": {"END"},
"END": set(),
}
state = {"stage": "START", "approved": False}
trace = ["START"]
def move(destination):
source = state["stage"]
if destination not in edges[source]:
raise ValueError(f"illegal edge {source} -> {destination}")
if destination == "EXECUTE" and not state["approved"]:
raise PermissionError("approval required")
state["stage"] = destination
trace.append(destination)
move("VALIDATE")
try:
move("EXECUTE")
except ValueError as error:
print("blocked:", error)
move("WAIT_APPROVAL")
try:
move("EXECUTE")
except PermissionError as error:
print("blocked:", error)
state["approved"] = True # fixture for an authenticated reviewer event
move("EXECUTE")
move("END")
print(" -> ".join(trace))
blocked: illegal edge VALIDATE -> EXECUTE
blocked: approval required
START -> VALIDATE -> WAIT_APPROVAL -> EXECUTE -> ENDWhat This Run Shows
- The first rejection enforces topology; the second enforces a condition on a permitted edge.
- State remains unchanged after each error, so an exception cannot accidentally advance the workflow.
- END has no outgoing edges, making completion an explicit property rather than a message convention.
These same invariants can be implemented with ordinary Python or a graph framework. Framework syntax should not obscure who owns state, which branches exist and which conditions are enforced.
From the Exercise to an Application
Experiment: Call move('EXECUTE') again after END.
The transition is rejected because END has no outgoing edges. A repeated message cannot reopen a completed task.
Summary / Key Takeaways
- A state graph makes execution explicit using state, nodes, edges, conditional routes, loops, parallel branches, and end states.
- Deterministic nodes and model-directed nodes can coexist, allowing flexible decisions inside controlled orchestration.
- Typed state makes it clear what information exists and which node may update it.
- Conditional routing should be bounded and testable; loops need explicit exit conditions.
- Orchestrator-worker is useful for dynamically decomposed parallel work, while evaluator-optimizer is useful for bounded revision against clear criteria.
- Graphs improve inspectability because developers can test transitions and failure paths instead of hiding the whole workflow in one prompt.
- Persistence and resume behavior build on the graph/state model but belong to the durable-execution layer.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.