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
| Property | While-Loop Agent | Graph-Based Agent |
| Debuggability | Hard — opaque loop iterations | Easy — visualize exact path through nodes |
| Persistence | Lost on crash | State can be saved/resumed at any node |
| Determinism | Low — LLM decides everything | High — transitions can be deterministic |
| Human-in-Loop | Awkward to implement | Natural — pause at any node, wait for approval |
| Testing | Difficult — full runs required | Easy — test individual nodes in isolation |
Anatomy of a Graph Agent
// Conceptual LangGraph Structure:
const graph = new StateGraph({
channels: { messages: [], plan: null, status: "pending" }
});
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", humanApproval); // Waits for human OK
// Edges define the flow:
graph.addEdge("planner", "executor");
graph.addEdge("executor", "reviewer");
graph.addConditionalEdge("reviewer", (state) => {
if (state.quality >= 0.8) return "human_gate";
return "executor"; // Loop back for another attempt
});
graph.addEdge("human_gate", END);
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
| Pattern | Structure | Use Case |
| Linear Pipeline | A → B → C → END | Sequential processing (research → write → edit) |
| Fan-Out/Fan-In | A → [B1, B2, B3] → C | Parallel execution (search 3 sources, then merge) |
| Retry Loop | A → B → (fail? → A) | Self-correcting code generation |
| Router | A → {B1 | B2 | B3} | Intent classification → specialized handler |
| Human-in-Loop | A → PAUSE → B | Approval gate before irreversible action |