Skip to content
AgenticAIWiki
  1. Learn
  2. Part 9
  3. 52. Graph-based orchestration
  4. 52.1

Lesson 52.1 · 1 of 6 · 6 min read · Reviewed 24 Nov 2026

Agents as state machines: nodes, edges and state

By the end, you can

  • Describe an agent as a state machine with nodes, edges and shared state.
  • Design a small state object that every node can read and update.

Lesson 51.3 introduced graph frameworks. This chapter builds the idea from the ground up, starting with the oldest tool in computing for describing control flow: the state machine.

Three parts

Part What it is Example in a coding agent
Node A unit of work: a model call, a tool call or plain code write, test, review
Edge A rule for what runs next after write, always go to test
State One shared object every node reads and updates {task, code, test_output, attempts}

A plain agent loopAgent loop: The cycle of calling the model, running any tools it requests, returning the results and repeating until it stops. (51.5) keeps all of this implicit: the “state” is the message list, and the “edges” are whatever the model decides next. A graph writes the structure down. You can draw it, review it and test each piece alone.

Nodes return updates, not whole states

A node is a function that takes the current state and returns only the fields it changed:

def write(state):
    code = draft_code(state["task"], state.get("test_output"))
    return {"code": code, "attempts": state["attempts"] + 1}

The runtime merges that update into the state, then follows the edge out of write. Most frameworks let you choose how a field merges: replace it (the default) or append to it, which suits a list of messages or a log of events.

Design the state first

Before you write any node, list the fields. A good state object:

  • holds everything a later node needs, because nodes share nothing else;
  • holds what a person would want to inspect when a run pauses (lesson 52.4);
  • is plain, serialisable data: strings, numbers, lists, small dicts. No open connections or file handles, because checkpoints must save it.

A worked example for a “fix the failing test” agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done.:

state = {
    "task": "make test_discount pass",
    "plan": None,          # set by plan
    "code": None,          # set by write
    "test_output": None,   # set by test
    "passed": False,       # set by test
    "attempts": 0,         # incremented by write
}

Reading the field list tells you most of what the graph does before you see a single edge.

Why bother with the structure

  • Reviewable: a teammate can read the graph and see every path, including the rare ones.
  • Testable: each node is a function. Feed it a state, check the update.
  • Traceable: every step is “node X ran, changed fields Y”. That is a ready-made traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps..
  • Mixable: a node can hold a whole agent loop inside it, so you keep flexibility where you need it and fixed paths everywhere else.

Common mistakes

  • State as a dumping ground. Fifty fields nobody reads. Keep only what nodes or reviewers use.
  • Hidden side channels. Nodes that pass data through globals or files break pause and resumeSession resumption: Continuing an earlier session by reloading its saved history or state..
  • Giant nodes. One node that plans, writes and tests is a plain loop with extra ceremony. Split it where you would want to see a step in the trace.

Key points

  • A graph agent is a state machine: nodes do work, edges decide what runs next, and a shared state object carries everything between them.
  • Each node reads the state and returns only the fields it changed; the runtime merges the update.
  • Design the state first. If a value is not in the state, no later node can see it, and no checkpoint can save it.
  • Small, well-named nodes make the graph easy to review, test and trace.
Hands-on labRuns in the Playground

Design the state for a coding graph

Design a plain, serialisable state object and nodes that return only the fields they change.

You will have: A state dict, two nodes and a checkpoint check that prints which fields each node changed.

Steps

  1. Run the starter: the checkpoint fails and write returns every field.
  2. Replace the live connection in the state with a plain id.
  3. Make write return only code and attempts.
  4. Run again and read which fields each node changed.
  5. Add a test node that reads code and returns passed and test_output.

Done when

  • Every checkpoint prints 'checkpoint ok'.
  • plan changes only plan; write changes only attempts and code.
  • The live connection stays outside the state, looked up by its id.

Open in the Playground No API key needed.

Starter code (Python)
import json

# Design the state first. Nodes share nothing else, and a checkpoint must be able to save it.
class DbConnection:
    """Stands in for a live connection: it cannot be turned into JSON."""
    def __init__(self, name):
        self.name = name


DB = {"main": DbConnection("main")}   # live objects live outside the state

# TODO: replace the live connection with plain data (store the id "main" under "db_id")
state = {"task": "make test_discount pass", "plan": None, "code": None,
         "test_output": None, "passed": False, "attempts": 0, "db": DbConnection("main")}


def plan(s):
    return {"plan": ["read pricing.py", "fix the rounding", "run tests"]}


def write(s):
    # TODO: return only the fields this node changes: code, and attempts + 1
    return dict(s, code="def apply_discount(p, pct): ...")


def checkpoint(s):
    try:
        return "checkpoint ok: " + str(len(json.dumps(s))) + " bytes"
    except TypeError as err:
        return f"checkpoint failed: {err}"


for node in (plan, write):
    update = node(state)
    print(f"fields changed by {node.__name__}: {sorted(update)}")
    state = {**state, **update}
    print(" ", checkpoint(state))
Show a solution
import json

# Design the state first. Nodes share nothing else, and a checkpoint must be able to save it.
class DbConnection:
    """Stands in for a live connection: it cannot be turned into JSON."""
    def __init__(self, name):
        self.name = name


DB = {"main": DbConnection("main")}   # live objects live outside the state

state = {"task": "make test_discount pass", "plan": None, "code": None,
         "test_output": None, "passed": False, "attempts": 0, "db_id": "main"}


def plan(s):
    return {"plan": ["read pricing.py", "fix the rounding", "run tests"]}


def write(s):
    return {"code": "def apply_discount(p, pct): ...", "attempts": s["attempts"] + 1}


def checkpoint(s):
    try:
        return "checkpoint ok: " + str(len(json.dumps(s))) + " bytes"
    except TypeError as err:
        return f"checkpoint failed: {err}"


for node in (plan, write):
    update = node(state)
    print(f"fields changed by {node.__name__}: {sorted(update)}")
    state = {**state, **update}
    print(" ", checkpoint(state))
Quick checkA test node needs the code a write node produced earlier in the run. How should it get it?
How sure are you?
Pick an answer and how sure you are