Step 2 of 4

LangGraph & State Machines

Model agents as graphs: typed state, reducers, conditional edges, checkpointers, human-in-the-loop, and multi-agent supervisors.

17 min read

The agent loop from the previous guide works, but real systems need more: branching logic, retries with limits, state that survives crashes, a human who can approve a risky step, and several specialized agents working together. LangGraph models all of that as an explicit state machine - a graph of nodes that read and update a shared state. You can see every path the agent can take, which makes it far easier to debug and control.

LangGraph basics#

The core idea#

State

A typed dictionary shared by every node - messages, intermediate results, counters. It's the single source of truth for a run.

Nodes

Plain functions that take the current state and return an update. A node might call an LLM, run a tool, or do pure Python.

Edges

What runs next. Normal edges always go A → B; conditional edges call a function that inspects state and picks the next node.

Typed state and reducers#

State is declared as a TypedDict. By default, a node's returned value overwrites a key. A reducer changes that - for example, add_messages appends new messages (and updates existing ones by id) instead of replacing the list:

from typing import Annotated, TypedDict
from langgraph.graph.message import add_messages

class State(TypedDict):
    messages: Annotated[list, add_messages]  # reducer: append, don't overwrite
    attempts: int                            # plain key: last write wins

A tool-calling agent as a graph#

from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import InMemorySaver

llm_with_tools = llm.bind_tools(tools)          # any LangChain chat model

def agent(state: State) -> dict:
    return {"messages": [llm_with_tools.invoke(state["messages"])]}

builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)  # → "tools" or END
builder.add_edge("tools", "agent")                        # loop back after tools

graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "user-42"}, "recursion_limit": 20}
graph.invoke({"messages": [("user", "What's 17% of 2,340?")]}, config)
  1. 01START
  2. 02agentLLM decides
  3. 03tools_conditionTool call requested?
  4. 04toolsExecute, append results

↺ tools feeds back into START

The same ReAct loop - but now it's an explicit graph with a checkpointer and a recursion limit.

Checkpointers: memory and fault tolerance#

Compiling with a checkpointer saves the state after every step, keyed by a thread_id. That one feature gives you:

  • Conversation memory - call the graph again with the same thread and it continues where it left off.
  • Fault tolerance - resume after a crash from the last completed step.
  • Time travel - inspect or replay any earlier state while debugging.
  • Human-in-the-loop - pause indefinitely and resume later.

Use InMemorySaver for development, and a durable backend (SQLite or Postgres checkpointers) in production.

TypedDict
A Python type hint that describes a dictionary's expected keys and value types - LangGraph uses it to define the shape of shared agent state.
Reducer
A function that controls how a new value merges into existing state - e.g., appending messages to a list instead of replacing it.
Checkpointer
A component that saves the graph's state after each step, enabling conversation memory, crash recovery, time-travel debugging, and human-in-the-loop pauses.
Subgraph
A compiled LangGraph graph used as a single node inside a larger graph - the standard way to compose and test multi-agent systems independently.

Human-in-the-loop#

Call interrupt() inside a node to pause the graph and surface a value to your application. The run stays saved in the checkpointer until you resume it with a Command:

from langgraph.types import interrupt, Command

def send_refund(state: State) -> dict:
    decision = interrupt({"action": "refund", "amount": state["amount"]})
    if decision != "approve":
        return {"messages": [("assistant", "Refund cancelled by reviewer.")]}
    ...  # perform the refund

# Later, after a human clicks Approve:
graph.invoke(Command(resume="approve"), config)

Design patterns that keep graphs healthy#

  1. 1Small nodes, one responsibility each - easier to test, retry, and reuse.
  2. 2Put retries inside a loop with an explicit counter in state and an exit condition.
  3. 3Always set a recursion limit so a confused agent can't loop forever.
  4. 4Keep state minimal and typed; don't stuff whole documents in when an id will do.
  5. 5Put approval gates (interrupt) in front of any irreversible or expensive action.
  6. 6Stream intermediate steps to the UI so users see progress on long runs.

Multi-agent systems in LangGraph#

A multi-agent system in LangGraph is a graph whose nodes are themselves agents (often compiled subgraphs), coordinated by a router or supervisor.

Router / supervisorReads the request, picks the next agent
  • ResearchSearch + retrieval tools
  • CodingCode execution sandbox
  • AnalysisSQL + dataframes
  • WriterFinal response
Specialists report back to the supervisor, which decides whether to call another agent or finish.

The mechanics:

  • Message passing: agents share the messages list (or a structured field) in state, so each one sees what the others produced.
  • Hand-offs: a node can return Command(goto="coding", update={...}) to route to another agent and update state in one step.
  • Tools per agent: give each specialist only the tools it needs. Fewer tools means better tool selection.
  • Memory: short-term memory is the thread's checkpointed state; long-term memory (facts about a user across threads) lives in a separate store.
  • Human-in-the-loop: an approval node between "writer" and "send" catches bad output before it leaves the system.
  • Debugging: stream updates to watch each node's state changes; replay from checkpoints; trace every LLM call with an observability tool.
from typing import Literal
from langgraph.types import Command

def supervisor(state: State) -> Command[Literal["research", "coding", "writer", "__end__"]]:
    choice = router_llm.invoke(state["messages"]).next_agent   # structured output
    return Command(goto=choice if choice != "done" else "__end__")

Deployment: the compiled graph is just an object you call, so it can run inside any API server. For persistence, streaming, and background runs at scale, pair it with a durable checkpointer and a task queue (or a managed LangGraph platform).

LangGraph interview handbook#

Why model an agent as a graph instead of a while-loop?

The graph makes control flow explicit and inspectable: you can see every possible path, add deterministic steps between LLM calls, put limits on cycles, checkpoint every step, and pause for humans. A while-loop hides all of that in code.

What is state, and why TypedDict?

State is the shared data every node reads and updates. A TypedDict (or Pydantic model) documents its shape, catches key typos, and lets you attach reducers per key.

What does a reducer do?

It defines how a node's update merges into existing state for a key. Without one, the new value overwrites. add_messages appends messages and replaces ones with matching ids; operator.add concatenates lists.

Normal edge vs conditional edge?

A normal edge always goes to the same next node. A conditional edge runs a function on the current state and returns the name of the next node - that's how branching and loops are expressed.

How do you create a loop, and how do you make sure it ends?

Add an edge from a later node back to an earlier one (e.g., tools → agent). Ensure termination with an exit condition in the conditional edge (e.g., no tool calls → END), a counter in state, and a recursion_limit in the run config.

What is a checkpointer and what does it enable?

It persists state after each super-step under a thread_id. It enables multi-turn memory, resuming after failures, time-travel debugging, and human-in-the-loop pauses.

How does human-in-the-loop work?

A node calls interrupt(payload), which pauses the run and returns the payload to the caller. The state is saved by the checkpointer. The app later resumes with graph.invoke(Command(resume=value), config), and interrupt() returns that value inside the node.

What streaming modes exist and when would you use them?

values streams the full state after each step; updates streams only what each node changed (great for progress UIs and debugging); messages streams LLM tokens as they're generated (great for chat UIs).

What are subgraphs for?

A compiled graph can be used as a node inside another graph. That lets you build and test each agent independently, then compose them - the standard way to structure multi-agent systems.

Short-term vs long-term memory in LangGraph?

Short-term memory is the thread's state, persisted by the checkpointer. Long-term memory spans threads - facts or preferences about a user - and is kept in a separate store, searched and written by nodes as needed.

How do you handle a tool that fails?

Catch the error in the tool node and return it as a tool message so the model can adapt; track attempts in state; route to a fallback or a human after N failures. Don't let raw exceptions crash the whole run.

Supervisor vs network (swarm) architectures?

A supervisor centralizes routing - simpler to reason about and debug. In a network, agents hand off to each other directly - more flexible, but paths are harder to predict. Start with a supervisor.

Papers behind this guide

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.