Skip to main content
LearnMLAcademy
Advanced10 min read

Agent Workflows, State Machines & Graphs

Build reliable agent workflows, cyclical state graphs, and checkpoints, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

Elements of an agent state graph
ElementPurposeHow to test it
NodePerforms one bounded operationGiven state, assert output update
EdgeAllows a named transitionAssert legal source and destination
StateCarries typed task informationValidate schema and ownership of updates
Conditional routeSelects a branch from evidenceTest every condition and fallback
LoopRepeats work while progress is possibleAssert progress rule and maximum count
Parallel branchRuns independent subtasks togetherTest isolation, join and conflict handling
ENDMarks a completed or safely stopped runAssert final status and required outputs

Move between states through checked transitions

  1. Define typed state containing inputs, intermediate results, status, counters, and the information each node may update.

  2. Create nodes for deterministic work, model-directed decisions, tools, validation, and human review; connect them with named edges.

  3. Add conditional routing, bounded loops, parallel branches, and explicit stop rules only where the task needs them.

  4. Use patterns such as orchestrator-worker for parallel subtasks and evaluator-optimizer for bounded revision.

  5. 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?

START
typed task state
Plan
model-directed route
Search
tool node
More
loop ↺
Enough
write
END
complete / safe stop
Every node receives and updates defined state. Conditional edges expose why the run searches again, requests review, writes, or ends.

Instructional figure

Two reusable graph patterns

When does work fan out, and when does one result loop through evaluation?

Orchestrator → parallel workers → join

Orchestrator
↙ ↓ ↘
Worker A
Worker B
Worker C
↘ ↓ ↙
Merge

Generate → evaluate → bounded revision

Draft
Evaluator
Revise ≤ N
Accept / stop
Orchestrator-worker parallelizes independent subtasks. Evaluator-optimizer revises one output against criteria and must have a revision limit.

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.

Illustrative framework fragment — external dependency/setup required
graph.add_edge("plan", "search")
graph.add_conditional_edges(
    "validate", route,
    {"enough": "write", "more": "search", "stop": END}
)
Learner note: Illustrative graph-building fragment. It requires a graph framework and surrounding state/node definitions; it is not standalone Python.

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.

transition_allowed = edge_exists AND guard_passes
Both checks are necessary. A structurally valid WAIT_APPROVAL → EXECUTE edge is still denied while approved=False.
  1. Attempt VALIDATE → EXECUTE. There is no edge, so the runtime rejects it.
  2. Enter WAIT_APPROVAL and try the legal execution edge without approval. The guard rejects it.
  3. Set approved=True to represent a trusted reviewer event, then execute and finish.
  4. Inspect the trace: rejected attempts do not change the current state.

The approval edge is guarded; the shortcut does not exist

START goes to VALIDATE, then WAIT_APPROVAL. The guarded approved edge reaches EXECUTE and END. Rejection can end without execution; there is no validation-to-execution shortcut.STARTVALIDATEWAIT_APPROVALapprovedEXECUTEENDreject× no edge
Follow solid arrows for allowed transitions. The dashed red path is a prohibited shortcut, not an executable edge. Rejection can finish without a write.

Follow solid arrows for allowed transitions. The dashed red path is a prohibited shortcut, not an executable edge. Rejection can finish without a write.

Complete Python ExercisepythonRunnable
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))
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
blocked: illegal edge VALIDATE -> EXECUTE
blocked: approval required
START -> VALIDATE -> WAIT_APPROVAL -> EXECUTE -> END
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. The first rejection enforces topology; the second enforces a condition on a permitted edge.
  2. State remains unchanged after each error, so an exception cannot accidentally advance the workflow.
  3. 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

From the Exercise to an Application
SituationPractical choiceImportant qualification
Approval-gated writeUse a guarded transitionRevalidate authority and the exact action at execution time.
Parallel evidence gatheringMerge results by stable IDs/provenanceDetect conflicting facts instead of overwriting them.
Retry loopRecord attempts and progressEvery cycle needs a reachable stop condition.
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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Agent Workflows, State Machines & Graphs"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the main benefit of explicit state in an agent graph?
Question 2 of 5conceptual
In an evaluator-optimizer pattern, what happens after the evaluator rejects a draft?
Question 3 of 5practical selection
Which pattern best fits dynamically dividing a report into an unknown number of sections and processing them in parallel?
Question 4 of 5debugging/diagnostic
A graph contains a `search → validate → search` cycle with no maximum iterations or success condition. What is wrong?
Question 5 of 5conceptual
Which concern belongs mainly to the next durability layer rather than basic graph structure?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the main benefit of explicit state in an agent graph?▼

Correct Answer: It makes the information passed between nodes and the allowed updates inspectable and testable

Typed state makes workflow data and transitions explicit rather than hiding everything inside one prompt.

2In an evaluator-optimizer pattern, what happens after the evaluator rejects a draft?▼

Correct Answer: Feedback is returned for a bounded revision cycle

Evaluator-optimizer loops use explicit feedback to revise an output until success criteria or a stop rule is reached.

3Which pattern best fits dynamically dividing a report into an unknown number of sections and processing them in parallel?▼

Correct Answer: Orchestrator-worker

An orchestrator can decompose the task at runtime and delegate parallel subtasks to workers.

4A graph contains a `search → validate → search` cycle with no maximum iterations or success condition. What is wrong?▼

Correct Answer: The loop is unbounded

Loops are valid, but they need explicit exit conditions and budgets to prevent infinite execution.

5Which concern belongs mainly to the next durability layer rather than basic graph structure?▼

Correct Answer: Persisting a checkpoint so the graph can resume after a process restart

Persistence and restart/resume behavior build on the state graph but are part of durable execution.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next