Skip to main content

State Machines & Graph Agents — The Agentic Control Loop

[ ABORT TO HUD ]
SEQ. 1
SEQ. 2
SEQ. 3
SEQ. 4
SEQ. 5

State Machines & Graph Agents

🔄 The Agentic Control Loop⏱ 10 min⭐ 70 BASE XP⌨ HANDS-ON LAB

Modeling Agents as Graphs

The most reliable production agents are not free-form loops - they are state machines modeled as directed graphs. This is the core insight behind LangGraph and similar frameworks.

Why Graphs Beat While-Loops

PropertyWhile-Loop AgentGraph-Based Agent
DebuggabilityHard - opaque loop iterationsEasy - visualize exact path through nodes
PersistenceLost on crashState can be saved/resumed at any node
DeterminismLow - LLM decides everythingHigh - transitions can be deterministic
Human-in-LoopAwkward to implementNatural - pause at any node, wait for approval
TestingDifficult - full runs requiredEasy - test individual nodes in isolation

Anatomy of a Graph Agent

// LangGraph v1.x Structure (Annotation.Root + START/END + interrupt):
const AgentState = Annotation.Root({
  messages: Annotation<string[]>(), plan: Annotation<string>(), quality: Annotation<number>()
});

const graph = new StateGraph(AgentState);
graph.addNode("planner",    plannerAgent);  // Creates a plan
graph.addNode("executor",   executorAgent); // Executes plan steps  
graph.addNode("reviewer",   reviewerAgent); // Reviews output quality
graph.addNode("human_gate", () => ({ approved: interrupt("Approve plan?") })); // Dynamic interrupt()

// Edges define the flow:
graph.addEdge(START,      "planner");
graph.addEdge("planner",  "executor");
graph.addEdge("executor", "reviewer");
graph.addConditionalEdges("reviewer", (state) => {
  if (state.quality >= 0.8) return "human_gate";
  return "executor"; // Loop back for another attempt
});
graph.addEdge("human_gate", END);
const app = graph.compile({ checkpointer: new InMemorySaver() }); // PostgresSaver in production

LangGraph v1.x & LangChain v1 Standards: For standard tool-calling loops without custom topologies, import create_agent from langchain.agents (which replaces the deprecated langgraph.prebuilt.create_react_agent). For custom state machines requiring Human-in-the-Loop pauses, call interrupt(payload) dynamically inside any node (replacing legacy NodeInterrupt and static compiler breakpoints) and resume execution via Command(resume=value) backed by InMemorySaver (local dev) or PostgresSaver (production).

Key Concepts

  • Nodes: Individual processing units - can be LLM calls, tool executions, or pure functions.
  • Edges: Connections between nodes. Can be unconditional (always follow) or conditional (branch based on state).
  • State: A shared data structure (often a TypedDict or Pydantic model) that flows through the graph.
  • Checkpoints: Snapshots of state at each node - enables time-travel debugging, persistence, and resumption.
💡 Key Insight: The graph forces you to think about your agent architecture before writing code. Drawing the graph on a whiteboard first is the single best practice for building reliable agents.

Common Graph Patterns

PatternStructureUse Case
Linear PipelineA → B → C → ENDSequential processing (research → write → edit)
Fan-Out/Fan-InA → [B1, B2, B3] → CParallel execution (search 3 sources, then merge)
Retry LoopA → B → (fail? → A)Self-correcting code generation
RouterA → {B1 | B2 | B3}Intent classification → specialized handler
Human-in-LoopA → PAUSE → BApproval gate before irreversible action
⌨ HANDS-ON LABCompile LangGraph StateGraph with Checkpointer
⭐ +150 XP

Define a cyclical agent state machine using LangGraph v1.x with typed state schemas, conditional edges, and InMemorySaver checkpointing.

1Compile a StateGraph with nodes and entry points.
lab-sandbox — simulated environment
INFINITY LAB SANDBOX v2.6 — simulated shell
Type the command for the current objective. Helpers: "hint", "solution", "clear".
$
OBJECTIVE 1 / 1 — type "hint" if stuck
SYNAPSE VERIFICATION
QUERY 1 // 3
What is the primary advantage of graph-based agents over simple while-loop agents?
They are faster
They are cheaper
They provide debuggability, persistence, and deterministic control flow
They don't need an LLM