Module 1 · Thinking in graphs
StateGraph: nodes, edges, entry point
6 min read
A LangGraph graph is built in three stages: you declare the state, assemble nodes and edges with a StateGraph, then compile the whole into an executable object. This lesson details each piece on an example without an LLM, to see the mechanics clearly before adding a model.
The first graph
Here is an editorial workflow: write, review twice, publish. It is deliberately trivial — what matters is the structure.
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
topic: str
draft: str
revisions: int
log: Annotated[list[str], operator.add]
def write(state: State) -> dict:
return {"draft": f"Draft about {state['topic']}", "log": ["write"]}
def review(state: State) -> dict:
return {"revisions": state["revisions"] + 1, "log": [f"review #{state['revisions'] + 1}"]}
def good_enough(state: State) -> str:
return "publish" if state["revisions"] >= 2 else "review"
def publish(state: State) -> dict:
return {"draft": state["draft"].upper(), "log": ["publish"]}
builder = StateGraph(State)
builder.add_node("write", write)
builder.add_node("review", review)
builder.add_node("publish", publish)
builder.add_edge(START, "write")
builder.add_edge("write", "review")
builder.add_conditional_edges("review", good_enough, ["review", "publish"])
builder.add_edge("publish", END)
graph = builder.compile()
result = graph.invoke({"topic": "LangGraph", "draft": "", "revisions": 0, "log": []})
print(" → ".join(result["log"])) # write → review #1 → review #2 → publish
This script is the companion code's examples/01_first_graph.py file.
Nodes: functions that return an update
A node is a function (sync or async) that receives the current state and returns a partial dictionary: only the keys it wants to change.
writeonly returnsdraftandlog:topicandrevisionsare untouched.- A node never modifies the state in place (
state["draft"] = ...is a design error): it returns an update, which the engine applies. - A node with nothing to change can return
{}.
The name passed to add_node is the node's identifier in the graph. If omitted, LangGraph uses the function's name: builder.add_node(write) is equivalent to builder.add_node("write", write).
A node can also declare extra parameters that LangGraph injects: the run configuration (config: RunnableConfig) or the run context (runtime: Runtime[Context]), which we'll see in the next lessons.
Edges: what runs next
Three kinds of edges:
| Type | Method | Use |
|---|---|---|
| Fixed | add_edge("a", "b") | After a, always b |
| Conditional | add_conditional_edges("a", router, [...]) | After a, the router function chooses |
| Dynamic | Send(...) returned by a router | Launch N runs of a node in parallel (lesson 2.3) |
START and END are two virtual nodes: START is the entry point, END the end of execution. A graph can have several edges leaving START (several nodes start in parallel) and several paths leading to END.
The third argument of add_conditional_edges (the ["review", "publish"] list) declares the possible destinations. It isn't required at runtime, but it lets LangGraph draw the graph correctly and check its consistency at compile time. Get into the habit of providing it, or of annotating the router's return type with Literal["review", "publish"], which has the same effect.
Compilation
builder.compile() checks the structure (an edge to a nonexistent node, a missing entry point…) and returns a CompiledStateGraph. That is the object you run. Compilation is also when you plug in:
- a checkpointer (
compile(checkpointer=...)) for persistence — module 3; - a store (
compile(store=...)) for long-term memory — lesson 3.3; - static breakpoints (
interrupt_before=[...]) for debugging — module 4.
The StateGraph (the builder) and the compiled graph are two distinct objects: you modify the first, you run the second.
Running a graph
The compiled graph is a Runnable: it runs like any LangChain component.
| Method | Returns |
|---|---|
invoke(input) / await ainvoke(input) | The final state |
stream(input, stream_mode=...) / astream(...) | A stream of events during execution (lesson 5.1) |
The input is a dictionary matching the state schema. For graphs that can pause (module 4), we will use the version="v2" option, which returns a GraphOutput object cleanly separating the final value (.value) from pending interrupts (.interrupts).
The execution model: super-steps
LangGraph runs the graph in steps (super-steps). At each step:
- all active nodes run — in parallel if there are several;
- their updates are applied to the state, at the end of the step;
- outgoing edges determine the active nodes of the next step;
- if a checkpointer is configured, the state is saved.
Execution ends when no node is active anymore. Two important consequences:
- Two nodes in the same step don't see each other's updates: they all read the state as of the start of the step.
- If two nodes in the same step write the same key, you must tell the engine how to combine those writes: that is the role of reducers (next lesson). Without a reducer, LangGraph raises an error rather than arbitrarily keeping one of the two values.
Visualizing the graph
A compiled graph can draw itself. It is one of the most concrete benefits of the approach: your flow's documentation is generated from the code, so it can never be out of date.
print(graph.get_graph().draw_mermaid())
Paste the output into any Mermaid editor (GitHub and most documentation tools render it directly). Conditional edges appear dashed. In a notebook, graph.get_graph().draw_mermaid_png() produces an image directly.
Key takeaways
- Three stages: declare the state, assemble nodes and edges in a
StateGraph, compile.- A node returns a partial update; it never modifies the state in place.
- Fixed, conditional (routing function) or dynamic (
Send) edges;STARTandENDare virtual.- Execution proceeds in super-steps: active nodes in parallel, updates applied at the end of the step, optional save.
get_graph().draw_mermaid()documents the flow from the code.
Practice
- Run
examples/01_first_graph.pyand display its Mermaid diagram. - Add a
translatenode that also starts fromSTART, in parallel withwrite. Watch the order of entries inlog. - Remove the list of destinations from
add_conditional_edges: what happens to the diagram? Add aLiteralannotation to the router and compare.