Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 32 ยท LangGraph Workflows

LangGraph: State, Nodes and Edges

Learn the LangGraph model: a typed state, nodes that return updates, edges that route, and reducers that merge. Run a mini StateGraph stand-in in Python.

LangGraph is the library that powers LangChain agents, and you can use it directly when you want full control over the flow. Its idea is small and worth learning well: your program is a graph. A shared state object flows through it, nodes are functions that read the state and return updates, and edges decide which node runs next. Compared with a chain, a graph can branch, loop and pause, which is exactly what agents, approvals and multi-step workflows need.

LangGraph is not available on this site, so real code is read-only. The runnable examples use a tiny stand-in class, MiniGraph, that copies the shape of the real StateGraph API (add_node, add_edge, compile, invoke) in about thirty lines of Python, so you can run the ideas.

The three pieces

flowchart LR
    S(("START")) --> A["node: draft"]
    A --> B["node: polish"]
    B --> E(("END"))

A linear graph. State passes through each node.

  • State: a schema (a TypedDict or a pydantic model) describing the data the graph carries, for example {"topic": str, "draft": str}.
  • Node: a function node(state) -> dict. It returns only the fields it wants to change.
  • Edge: a connection from one node to the next. START and END are special markers for entry and exit.

Here is the real API:

Python
# Real LangGraph (read-only)
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    topic: str
    draft: str

def write_draft(state: State) -> dict:
    return {"draft": f"A short note about {state['topic']}."}

def polish(state: State) -> dict:
    return {"draft": state["draft"].upper()}

builder = StateGraph(State)
builder.add_node("write_draft", write_draft)
builder.add_node("polish", polish)
builder.add_edge(START, "write_draft")
builder.add_edge("write_draft", "polish")
builder.add_edge("polish", END)

graph = builder.compile()
print(graph.invoke({"topic": "rivers"}))
# {'topic': 'rivers', 'draft': 'A SHORT NOTE ABOUT RIVERS.'}

Building is declarative: you register nodes and edges, then compile() checks the graph (no unreachable nodes, no missing targets) and returns a runnable object. A compiled graph has the same invoke, stream and async methods as any LangChain runnable.

A mini StateGraph you can run

This stand-in has the same method names. It runs nodes in order, merges each returned dict into the state and stops at END.

Python Stand-in: a MiniGraph with the StateGraph shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each node returned only the key it changed; the graph merged it into the shared state.

Reducers: how updates merge

By default a returned key overwrites the old value. That is wrong for lists such as a message history, where you want to append. A reducer is a function (old, new) -> merged attached to a key through Annotated.

Python
# Real LangGraph (read-only)
import operator
from typing import Annotated, TypedDict

class State(TypedDict):
    log: Annotated[list[str], operator.add]   # lists are concatenated
    answer: str                                # plain keys are overwritten

For chat messages LangGraph provides add_messages, which appends new messages and also replaces a message that has the same id. MessagesState is a ready-made state with a single messages key using that reducer, and it is what create_agent builds on.

Python Stand-in: overwrite versus append with a reducer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without a reducer the second node wiped out the first node's log entry. With operator.add, both survive. This is the most common beginner surprise in LangGraph.

Why a graph instead of a chain?

Need Chain (pipe operator) Graph
Straight pipeline Perfect Works, but more code
Branch on a condition Awkward add_conditional_edges
Loop until done Not possible An edge back to an earlier node
Pause for a human Not possible Checkpoints and interrupt
Save and resume Manual Built in with a checkpointer
Several agents sharing state Manual Subgraphs and shared state

Branches and loops come next in conditional edges and loops.

Streaming and inspecting a graph

graph.stream(input) yields progress as nodes finish. With stream_mode="updates" you get each node's returned update; with "values" the full state after each step. For debugging, graph.get_graph().draw_mermaid() prints a Mermaid diagram of the compiled graph, which you can paste into docs.

Python
# Real LangGraph (read-only)
for update in graph.stream({"topic": "rivers"}, stream_mode="updates"):
    print(update)
# {'write_draft': {'draft': 'A short note about rivers.'}}
# {'polish': {'draft': 'A SHORT NOTE ABOUT RIVERS.'}}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a LangGraph node return?

    Nodes return partial updates, which the graph merges into the shared state.
  2. 2. What happens when two nodes both return the same key and it has no reducer?

    Without a reducer a key is overwritten; use Annotated with a reducer to merge.
  3. 3. What do START and END represent?

    They mark where execution enters and leaves the graph.
  4. 4. What does compile() do?

    compile checks the structure and returns a graph with invoke and stream methods.

Summary

  • A LangGraph program is a state flowing through nodes connected by edges.
  • Nodes return partial updates; reducers (operator.add, add_messages) decide how keys merge.
  • StateGraph(...).compile() yields a runnable with invoke and stream.
  • Graphs add branching, loops, pausing and persistence that plain chains lack.

Next: Conditional Edges and Loops