Graph or state machine: named steps, shared state, and explicit rules for what comes next

A state graph models a workflow as steps and transitions over shared state, with loops and exits written in code. Use it when the flow has branches, retries, or fallbacks that must be predictable.

State graph in 60 seconds

  • What: a set of named steps (nodes) joined by rules (edges), all reading and writing one shared state object.
  • Who decides the path: your code. Edges are conditions on the state, so every route is known and testable.
  • Best for: workflows with retries, quality gates, fallbacks, and loops that must end, such as grade-then-generate retrieval.
  • Weak spots: more design work up front, graphs that grow tangled, and state that is never validated.
  • Link to other work: the corrective RAG pattern is a small graph, and the same shape suits any step that grades its own input.

Where this type fits

State graphs belong with the patterns where your code decides the path: pipeline, router, parallel fan-out, and state graph. It is the most general of the four, since a pipeline is a graph with no branches and a router is a graph with one branch. Compare them on the orchestration hub.

The problem it solves

A straight pipeline cannot say "if this step went badly, try again, and if it still fails, do something else". Teams then add the logic as nested conditions inside one function, or leave it to a model to improvise. The first becomes hard to read and the second becomes hard to predict.

Loops are the sharpest case. A workflow that retrieves, checks the result, and retrieves again if it is weak will loop forever on a hard question unless something counts the tries. If that counter is buried in prompts or scattered through code, loops end in surprising ways, or not at all.

A state graph makes the flow visible. Each step has a name and one job. Each transition is a small function of the state. You can draw the graph, test every edge, resume a run from any step, and see in logs exactly which route a request took.

How it works

  • Define the state. A single object holds everything steps need: the question, retrieved passages, grade, tries used, and the answer so far.
  • Define the nodes. Each node is a function that reads the state and returns changes to it. A node may call a model, a tool, or neither.
  • Define the edges. After each node, a rule looks at the state and names the next node. Rules can be fixed, or conditional.
  • Set the entry and exit. One start node, and one or more end nodes. Every path must reach an end.
  • Bound the loops. Keep a step counter in the state and give every cycle an exit that fires when it is used up.
  • Save the state. Store it after each node, so a run can be inspected, resumed, or replayed.
Retrieve and grade form a loop that is bounded by a try counter, with a fallback exit.

In the diagram, only one cycle exists, between retrieve and grade, and it has two exits. A good grade leaves toward generate. A weak grade with tries used up leaves toward the fallback. Because the exit condition is code, not a prompt, the loop cannot run past its limit.

Notice what the model does here. It may grade the passages and write the answer, but it never chooses the next node. That keeps behaviour predictable and makes the graph easy to test with fake model outputs.

A worked example

Acme runs a policy assistant. The question is "Can contractors claim travel expenses?" The graph allows at most two retrieval tries.

  • State at start: {"question": "Can contractors claim travel expenses?", "tries": 0, "passages": [], "grade": null}.
  • Retrieve (try 1): returns three passages about employee travel. tries becomes 1.
  • Grade: a model checks relevance. Result: weak, because the passages never mention contractors.
  • Edge rule: grade is weak and tries (1) is below the limit (2), so go back to retrieve with a rewritten query, "contractor expense policy".
  • Retrieve (try 2): returns a passage from the contractor handbook. tries becomes 2.
  • Grade: good. The rule sends the run to generate.
  • Generate: writes "Contractors may claim pre-approved travel, up to the limit in section 4," with a citation.
  • Output: the answer, and a log of the route: retrieve, grade, retrieve, grade, generate, done.

Had the second grade also been weak, the rule would have sent the run to the fallback, which says the policy could not be found and offers to ask a person. Either way, the run ends.

Building it

A small state graph with a bounded retry loop (illustrative) (python)
MAX_TRIES = 2        # the loop's hard limit
MAX_NODE_VISITS = 10 # global safety net against any graph mistake

def retrieve(state):
    query = state.get("rewritten") or state["question"]
    # Placeholder: search the index and return passages.
    state["passages"] = store.search(query, k=4)
    state["tries"] += 1
    return state

def grade(state):
    # Placeholder: a model returns "good" or "weak" for the passages.
    state["grade"] = llm.generate_json(GRADE_PROMPT, state)["grade"]
    if state["grade"] == "weak":
        state["rewritten"] = llm.generate(REWRITE_PROMPT, state["question"])
    return state

def generate(state):
    state["answer"] = llm.generate(ANSWER_PROMPT, state["question"], state["passages"])
    return state

def fallback(state):
    state["answer"] = "I could not find this in the policy. A person can help."
    return state

# Edges are plain code: each returns the name of the next node.
def after_grade(state):
    if state["grade"] == "good":
        return "generate"
    return "retrieve" if state["tries"] < MAX_TRIES else "fallback"

NODES = {"retrieve": retrieve, "grade": grade, "generate": generate, "fallback": fallback}
EDGES = {"retrieve": lambda s: "grade", "grade": after_grade,
         "generate": lambda s: "done", "fallback": lambda s: "done"}

def run(question: str):
    state = {"question": question, "tries": 0, "passages": [], "grade": None}
    node, visits, route = "retrieve", 0, []
    while node != "done":
        visits += 1
        if visits > MAX_NODE_VISITS:
            state["answer"] = "Stopped: too many steps."
            break
        state = NODES[node](state)
        route.append(node)
        checkpoint.save(state, route)   # lets you resume or replay a run
        node = EDGES[node](state)
    return state["answer"], route

store, llm, checkpoint, and the prompts are placeholders. Two limits appear on purpose: one for the retry loop and one for the whole run, so a graph mistake cannot spin forever.

Design decisions

  • State shape: keep one typed object with a small set of fields. Avoid putting whole documents in it; store references and load them when needed.
  • Node size: one job per node, so you can test, retry, and time it alone. Split nodes that mix a model call with side effects.
  • Edge logic: keep edges as pure functions of state. Do not call a model inside an edge. If a model must decide, make that a node that writes a field, and let the edge read it.
  • Loop limits: give every cycle its own counter and a global visit cap. Both should end in a named fallback, not an error.
  • Persistence: save state after each node. This allows resuming after a crash and pausing for a human checkpoint. Use a database or queue, not process memory.
  • Versioning: store the graph version with each run. Changing a node while runs are paused can break them, so resume old runs on the old graph.
  • Side effects: make nodes that change the outside world idempotent, since replays and retries will call them again. See idempotency.

Measuring it

  • Path frequency: count how often each route through the graph occurs. Rare paths deserve tests, and common slow paths deserve tuning.
  • Loop count distribution: the share of runs that retry once, twice, or hit the limit. A high limit-hit rate points to weak retrieval or a harsh grader.
  • Fallback rate: the share of runs that end at the fallback, and how many of those a person could have answered.
  • Node latency and cost: time and tokens per node, so you know which step to optimise.
  • Grader agreement: compare the model's grades with human grades on a sample. A grade node that is wrong sends the whole graph the wrong way.
  • End-to-end quality: a graded sample of final answers, compared with a no-loop version of the same flow.

When to use it, and when not to

SituationUse this type?Why
Workflow with retries, quality gates, and a fallbackYesEdges express the rules clearly and the loops are bounded.
Steps that always run in the same orderNoA pipeline is simpler and easier to read.
Long runs that pause for approval or resume after a crashYesSaved state after each node makes pause and resume natural.
Open-ended goals where the steps cannot be listedNoLet a supervisor or single agent choose steps at run time.
A choice between several fixed pathsNot aloneA router is the lighter fit. Use a graph if paths also loop.
Regulated flows that need an audit trailYesThe saved route and state show exactly what happened and why.

Trade-offs

DimensionEffectWhat to do about it
QualityGates and retries raise answer quality on hard inputs. A poor grader can reject good work.Measure the grader against human grades and tune its threshold.
LatencyEach loop pass adds model calls and time. Easy requests pay almost nothing.Keep limits low and show progress for slow paths.
CostPredictable, since every path and limit is known up front.Compute worst-case cost from the graph and set budgets to match.
ComplexityMore design effort than a pipeline, and graphs can become tangled.Keep nodes small, draw the graph in the docs, and review changes to edges.
Failure modesLoops that never end, state that goes stale, and edges that miss a case.Add counters, validate state, and test every edge with fake outputs.

A pipeline is a graph with no branches or loops. Move to a state graph the moment you need a gate or a retry. A router is a graph with a single branch near the start. If your flow has only that, keep the router.

Against a supervisor, the difference is who writes the path. In a graph, you write it, so it is predictable and cheap to test. A supervisor lets a model write it, which handles open-ended goals but is harder to bound. The corrective RAG page shows the graph idea applied to retrieval.

What this means for your role

Common mistakes

Further reading

A state graph turns a workflow into something you can read, test, and resume. Use it when the flow needs branches and loops, and keep every loop on a short leash.

Search topics

↑↓ to move · Enter to open · Esc to close