Why a graph instead of a loop
The prebuilt agent you built in earlier lessons hides its control flow. That is fine until you want a branch that only runs on certain tool results, a human approval step, or a loop that retries a failed lookup up to three times. Hiding the loop means patching around it; LangGraph makes the loop the thing you write.
A LangGraph application is three ideas. State is a typed object, usually a dictionary or dataclass, that every node receives and returns. Nodes are ordinary Python functions that take the current state and emit updates. Edges connect nodes, either unconditionally or through a routing function that reads the state and chooses the next node by name. The runtime starts at a named entry node, applies each node's returned updates to the state, follows the chosen edge, and stops when a node signals that no further step is needed.
Because the graph is data, you can print its structure, serialize it, and run the same state object through two different graphs to compare behavior. That property makes LangGraph a good fit not only for autonomous agents but also for stepwise workflows where an agent's judgement is only needed at one or two decision points.
State: the single object everything shares
Deciding the shape of state is the real design work. Put in it everything a node might need to read and nothing that is merely convenient to pass along. A chat agent usually needs the message list, the name of the last tool called, and a counter that bounds how many steps the loop may take. A document pipeline usually needs the current text, metadata about the source, and any errors collected so far.
from typing import Annotated, Sequence
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
class AgentState(TypedDict):
messages: Annotated[Sequence, "append new messages, keep history"]
next_tool: str
steps_remaining: int
def update_messages(
existing: Sequence,
new: Sequence,
) -> Sequence:
return list(existing) + list(new)
class AgentStateWithReducer(TypedDict):
messages: Annotated[Sequence, update_messages]
next_tool: str
steps_remaining: int
The Annotated reducer is the part beginners skip and then fight with later. Without a reducer, a node that returns messages replaces the whole list, which quietly discards history when two nodes both return messages. The reducer tells the runtime to append instead, which is almost always what you want for conversation state. Counters and flags usually need no reducer, because replacing them with a fresh value is the correct semantics.
Nodes and unconditional edges
A node is a function with a narrow contract: read what you need from state, do one thing, return a dictionary of keys to update. Returning nothing is legal and means the node has no effect on state, which is useful for pure side effects such as writing a log line.
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode
@tool
def search(query: str) -> str:
"""Search for current information. Returns short text snippets."""
return f"Results for '{query}': LangGraph graphs route state between typed nodes."
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [search]
model_with_tools = model.bind_tools(tools)
tool_node = ToolNode(tools)
def call_model(state: AgentState):
response = model_with_tools.invoke(state["messages"])
return {
"messages": [response],
"next_tool": response.tool_calls[0]["name"] if response.tool_calls else "",
"steps_remaining": state["steps_remaining"] - 1,
}
def should_continue(state: AgentState) -> str:
last = state["messages"][-1]
if getattr(last, "tool_calls", None):
return "tools"
return "end"
graph = StateGraph(AgentStateWithReducer)
graph.add_node("agent", call_model)
graph.add_node("tools", tool_node)
graph.add_edge(START, "agent")
graph.add_conditional_edges(
"agent",
should_continue,
{"tools": "tools", "end": END},
)
graph.add_edge("tools", "agent")
app = graph.compile()
That graph has exactly two nodes and one branch, and it reproduces the prebuilt ReAct agent from earlier lessons. The difference is that every piece is now named and inspectable. should_continue is a plain function you can unit test with a fake message list. call_model is a plain function you can call with a stubbed model. If the agent loops too many times, the fix is a condition on steps_remaining, which you can read directly in the state rather than inferring from logs.
Conditional edges and the routing contract
The routing function returns a string that must match one of the keys in the mapping you pass alongside it. Returning a name that is not in the mapping raises immediately, which is the behavior you want: a typo in a route name should fail loudly in development, not silently skip a branch in production.
| Route | Meaning | Typical guard |
|---|---|---|
tools | Model emitted tool calls, execute them | Tool calls present on last message |
end | Model produced a final answer | No tool calls, or budget exhausted |
human | Pause for approval before a side effect | Tool name in a sensitive set |
retry | Transient failure, try the node again | Retry counter greater than zero |
The approval route is worth building once even if your current agent does not need it. Interrupting before a write tool executes turns an autonomous agent into a supervised one, which is the difference between something you can run on real data and something you only run on test data. LangGraph supports human-in-the-loop patterns that persist the state at the interrupt point, let a person approve or edit the pending tool call, and resume the graph with that decision folded in.
from langgraph.checkpoint.memory import MemorySaver
def route_to_human_or_tools(state: AgentState) -> str:
last = state["messages"][-1]
if not getattr(last, "tool_calls", None):
return "end"
names = {tc["name"] for tc in last.tool_calls}
if names & {"send_email", "delete_record"}:
return "human"
return "tools"
graph = StateGraph(AgentStateWithReducer)
graph.add_node("agent", call_model)
graph.add_node("tools", tool_node)
graph.add_conditional_edges(
"agent",
route_to_human_or_tools,
{"tools": "tools", "human": "tools", "end": END},
)
graph.add_edge("tools", "agent")
memory = MemorySaver()
app = graph.compile(checkpointer=memory)
Notice that the human branch reuses the tools node in this sketch; the approval gate itself comes from the checkpointer and an interrupt, not from a second executor. The important structural point is that routing decisions live in one function you can read top to bottom, rather than being distributed across callbacks inside a framework loop.
When not to reach for a graph
LangGraph is a sharp tool and therefore not the right one for every problem. If your workflow is a straight line from input to output with no branching and no state that outlives a single call, a plain function chain is shorter, faster to test and easier to read. If you need a loop but not durability, the prebuilt agent from earlier lessons already gives you one in a single line of code. And if your team has never debugged a state machine, introducing one under a deadline multiplies the debugging surface at the worst possible moment.
The threshold worth remembering is this: reach for a graph when control flow must be visible, when a human needs to approve or edit a step mid-run, or when a run must survive a process restart. Those three needs are exactly what the graph and checkpointer buy you. Everything else is ceremony, and a thousand lines of node definitions around a two-step pipeline is a maintenance cost with no corresponding benefit. Build the simplest version that works, measure where the control flow actually becomes confusing, and let that measurement tell you when to introduce the graph.
Running the graph and reading the trace
Invocation takes a state-shaped input plus a config that carries the thread identifier when you are using a checkpointer.
config = {"configurable": {"thread_id": "lesson-1"}}
initial = {
"messages": [HumanMessage("What is LangGraph routing?")],
"next_tool": "",
"steps_remaining": 5,
}
result = app.invoke(initial, config=config)
for message in result["messages"]:
print(type(message).__name__, "->", message.content[:120])
The streamed variant, app.stream(..., stream_mode="updates"), emits a dictionary per node invocation, which is the fastest way to see which node ran when an answer looks wrong. Add a print inside each node during development if you need finer granularity; the state object carries enough information that a single well-placed log line usually identifies the misbehaving step.
Checkpointing deserves its own note. With a memory checkpointer, raising the interrupt, approving, and calling app.invoke(None, config) again resumes from exactly where the graph paused, with all prior state intact. Swap the memory saver for a Postgres-backed checkpointer and the same code survives a process restart, which is how you get durable, resumable workflows without writing your own persistence layer.
Common Mistakes
Omitting an Annotated reducer on the message list and losing history when two nodes return messages
Fix: Declare messages with a reducer that appends, so node updates combine instead of overwrite
Returning a route name that does not match the mapping passed to add_conditional_edges
Fix: Keep route strings in constants shared by the router and the mapping, and test the router with fake states
Packing the entire application into one node that calls the model and the tools itself
Fix: Split model calls, tool execution and side effects into separate nodes so each can be tested and branched independently
Building unbounded loops and discovering them through API bills
Fix: Put a steps_remaining counter in state and let the router end the graph when it hits zero
Best Practices
- Design state first; the node functions usually become obvious once the shared object is right
- Give every edge a name you would be comfortable reading in a stack trace
- Unit test routing functions with fabricated states before compiling the graph
- Log stream_mode updates during development so node order is visible without a debugger
- Start with a memory checkpointer and swap the backend only when durability across restarts is required
Interview Questions
Q1: What problem does a LangGraph node reducer solve?
When two nodes update the same key, the default behavior is replacement, which can discard prior messages. A reducer defines how updates combine, so appending to a message history becomes the explicit, correct semantics.
Q2: How do conditional edges differ from regular edges?
A regular edge always proceeds to a fixed next node. A conditional edge calls a routing function that reads the current state and returns the name of the next node, enabling branching, loops and early termination.
Q3: How would you add a human approval step before a destructive tool runs?
Route to an interrupt when the pending tool call is in a sensitive set, persist the state with a checkpointer, resume after the person approves or edits, and let the tools node execute the surviving calls.
Q4: Why is a graph representation easier to debug than a framework's hidden agent loop?
Node names, route strings and the state object are all visible data. You can print the compiled graph structure, stream per-node updates, and unit test each function in isolation.
Key Takeaways
- State is a typed object; reducers define how updates to shared keys combine
- Nodes are ordinary functions that read state and return partial updates
- Conditional edges use a routing function whose return value names the next node
- Routers should consult budget counters so runaway loops end predictably
- A checkpointer plus an interrupt gives you approval gates and durable resumable runs
- Stream per-node updates during development to see control flow without a debugger
- The prebuilt agent is a special case of the graphs you can now write by hand