Stateful agents with LangGraph

Graphs, typed state, reducers, conditional edges, checkpointers and threads, with a ReAct agent and a custom workflow.

Advanced about 6 h

The picture

  1. 01

    State

    typed dict + reducers

  2. 02

    Nodes

    functions

  3. 03

    Edges

    static + conditional

  4. 04

    Compile

    with a checkpointer

  5. 05

    Invoke

    per thread_id

  6. 06

    Inspect

    history, replay

The mental model

LangGraph models an agent as a graph: nodes are functions that read the shared state and return updates; edges decide what runs next. State fields can have reducers that define how updates merge (for example, append messages rather than overwrite). Because the whole run is explicit state moving through nodes, it can be saved, resumed, inspected and forked.

A tool-using agent as a graph

from typing import Annotated, TypedDict
from langchain_anthropic import ChatAnthropic
from langchain_core.tools import tool
from langgraph.graph import StateGraph, START
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver

@tool
def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b

tools = [multiply]
llm = ChatAnthropic(model="claude-sonnet-5-5").bind_tools(tools)

class State(TypedDict):
    messages: Annotated[list, add_messages]          # reducer: append

def agent(state: State):
    return {"messages": [llm.invoke(state["messages"])]}

g = StateGraph(State)
g.add_node("agent", agent)
g.add_node("tools", ToolNode(tools))
g.add_edge(START, "agent")
g.add_conditional_edges("agent", tools_condition)    # to "tools" if the model called one, else END
g.add_edge("tools", "agent")
app = g.compile(checkpointer=MemorySaver())

cfg = {"configurable": {"thread_id": "demo-1"}}
out = app.invoke({"messages": [("user", "What is 23.5 times 18?")]}, cfg)
print(out["messages"][-1].content)

out = app.invoke({"messages": [("user", "Now double that.")]}, cfg)   # same thread: it remembers
print(out["messages"][-1].content)

The thread_id selects a conversation; the checkpointer stores state after each step. Swap MemorySaver for a SQLite or Postgres checkpointer to survive restarts.

A custom workflow with a bounded retry loop

from typing import Literal

class DraftState(TypedDict):
    task: str
    draft: str
    feedback: str
    attempts: int

def write(s: DraftState):
    prompt = s["task"] if not s.get("feedback") else f"{s['task']}\nFix these issues:\n{s['feedback']}\nPrevious:\n{s['draft']}"
    return {"draft": llm_text(prompt), "attempts": s.get("attempts", 0) + 1}

def review(s: DraftState):
    return {"feedback": check_draft(s["draft"])}              # "" means OK; ideally an objective checker

def decide(s: DraftState) -> Literal["write", "__end__"]:
    return "__end__" if not s["feedback"] or s["attempts"] >= 3 else "write"

w = StateGraph(DraftState)
w.add_node("write", write); w.add_node("review", review)
w.add_edge(START, "write"); w.add_edge("write", "review")
w.add_conditional_edges("review", decide)
workflow = w.compile()

Note the attempt cap in the routing function: loops in a graph must always be able to terminate.

Debugging with checkpoints

Every step is saved, so you can list the history of a thread, look at the state at any point, and resume from an earlier checkpoint with changed state to test a fix, which is far cheaper than re-running the whole task.

for snap in app.get_state_history(cfg):
    print(snap.next, len(snap.values["messages"]))

Streaming and observability

Stream node-by-node updates to a UI with app.stream(..., stream_mode="updates"), and connect a tracing backend so each run is inspectable.

Common mistakes

  • Putting large blobs (documents, images) in state, which bloats every checkpoint. Store references.
  • A conditional edge with no path to the end.
  • Mutating state in place instead of returning updates.

Exercises

  1. Build the agent above with two tools and a SQLite checkpointer; kill the process mid-run and resume.
  2. Fork a run from step 2 with a corrected tool result and compare the final answers.

You are done when you can…

  • Build a tool-using agent as an explicit graph and run it with a persistent thread
  • Write a custom graph with branching and a bounded retry loop
  • Replay or fork a run from a checkpoint to debug it