LangGraph Architecture and State Management

LangGraph's graph, state, nodes, edges, reducers and checkpointers, with a stateful RAG example.

Last Updated:

Module 19 · Lesson 2 of 2 · Advanced

LangGraph Architecture and State Management

LangGraph's graph, state, nodes, edges, reducers and checkpointers, with a stateful RAG example.

LangGraph is a library for building stateful, multi-step LLM applications as graphs. Nodes do work, edges decide what runs next, and a shared state carries data between them. A checkpointer saves the state after each step, which gives you conversation memory, the ability to pause for human approval, and recovery from failures. LangChain's agents are built on it. This lesson explains LangGraph's architecture and builds a stateful RAG graph.

What you will learn

  • LangGraph's core concepts: state, nodes, edges, conditional edges and reducers
  • How to build and compile a graph
  • How checkpointers and thread IDs give persistent state
  • How to build a RAG graph that retries retrieval when results are weak

Prerequisites

pip install -U langgraph langchain langchain-anthropic

Core concepts

ConceptMeaning
StateA typed dictionary shared by all nodes (for example question, documents, answer, messages)
NodeA function that receives the state and returns an update to it
EdgeA fixed transition from one node to the next
Conditional edgeA routing function that chooses the next node based on the state
ReducerHow a node's update is merged into the state (default: replace; add_messages: append messages)
START / ENDSpecial nodes marking entry and exit
CheckpointerSaves state after each step per thread, enabling memory and resumption

A first graph

from typing import TypedDict
from langgraph.graph import END, START, StateGraph

class State(TypedDict):
    text: str
    word_count: int

def count_words(state: State) -> dict:
    return {"word_count": len(state["text"].split())}      # return only the keys you update

graph = StateGraph(State)
graph.add_node("count_words", count_words)
graph.add_edge(START, "count_words")
graph.add_edge("count_words", END)
app = graph.compile()

print(app.invoke({"text": "LangGraph builds stateful workflows", "word_count": 0}))
{'text': 'LangGraph builds stateful workflows', 'word_count': 4}

A stateful RAG graph with a retry loop

This graph retrieves, checks whether the results are good enough, rewrites the query and retries once if not, then answers. Messages accumulate in the state with the add_messages reducer.

rag_graph.py
from typing import Annotated, TypedDict

from langchain.chat_models import init_chat_model
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from rag_helpers import embed
import numpy as np

model = init_chat_model("anthropic:claude-opus-5-5")
CHUNKS = ["Employees get 18 days of paid leave in their first year.",
          "Up to 5 unused leave days can be carried over.",
          "Expense claims must be submitted within 30 days."]
VECTORS = embed(CHUNKS)

class RagState(TypedDict):
    messages: Annotated[list, add_messages]    # conversation, appended by the reducer
    query: str
    docs: list[str]
    best_score: float
    attempts: int

def retrieve(state: RagState) -> dict:
    scores = VECTORS @ embed(state["query"], query=True)[0]
    top = np.argsort(-scores)[:2]
    return {"docs": [CHUNKS[i] for i in top], "best_score": float(scores[top[0]]),
            "attempts": state.get("attempts", 0) + 1}

def route(state: RagState) -> str:
    return "answer" if state["best_score"] >= 0.6 or state["attempts"] >= 2 else "rewrite"

def rewrite(state: RagState) -> dict:
    new_query = model.invoke(f"Rewrite as a short search query for HR policies: {state['query']}").text
    return {"query": new_query}

def answer(state: RagState) -> dict:
    sources = "\n".join(f"[{i}] {d}" for i, d in enumerate(state["docs"], start=1))
    reply = model.invoke([{"role": "system", "content": "Answer from the sources only, citing [n]."},
                          *state["messages"],
                          {"role": "user", "content": f"Sources:\n{sources}"}])
    return {"messages": [reply]}

graph = StateGraph(RagState)
graph.add_node("retrieve", retrieve)
graph.add_node("rewrite", rewrite)
graph.add_node("answer", answer)
graph.add_edge(START, "retrieve")
graph.add_conditional_edges("retrieve", route, {"answer": "answer", "rewrite": "rewrite"})
graph.add_edge("rewrite", "retrieve")
graph.add_edge("answer", END)
app = graph.compile(checkpointer=InMemorySaver())

config = {"configurable": {"thread_id": "user-42"}}            # one thread per conversation
question = "how much vacation do newbies get"
result = app.invoke({"messages": [{"role": "user", "content": question}], "query": question,
                     "attempts": 0}, config)
print(result["messages"][-1].text)
New employees get 18 days of paid leave in their first year [1].

How state and checkpointing work

  • Each node returns a partial update; LangGraph merges it into the state. Keys with a reducer (like messages) are combined; others are replaced.
  • The checkpointer stores the state after every step under the thread_id. Calling invoke again with the same thread continues from the saved state, so the message history persists across turns.
  • Inspect a thread's state with app.get_state(config), which is very useful when debugging.
  • InMemorySaver is for development; use a database-backed checkpointer (for example PostgreSQL or SQLite integrations) in production so state survives restarts.

Visualising the graph

print(app.get_graph().draw_mermaid())      # Mermaid diagram text you can render in many tools

Common errors and troubleshooting

  • A node's output overwrites data unexpectedly: return only the keys you want to change, and use reducers for lists that should accumulate.
  • Infinite loops: every cycle needs an exit condition (here attempts >= 2); LangGraph also enforces a recursion limit.
  • Memory does not persist: compile with a checkpointer and pass the same thread_id on every call.
  • Import errors: LangGraph evolves quickly; check the documentation for your installed version.

Key takeaways

  • LangGraph models an application as a graph of nodes sharing a typed state.
  • Conditional edges add branching and loops; reducers control how updates merge.
  • Checkpointers plus thread IDs give persistent, resumable state per conversation.
  • It is a natural fit for self-correcting RAG, agents and human-in-the-loop flows.

Frequently asked questions

LangGraph or plain Python?

For a simple pipeline, plain Python is easier. LangGraph pays off when you need persistence, branching and loops, streaming of intermediate steps, or human approval.

Can nodes call any code?

Yes. Nodes are ordinary Python functions: call databases, APIs, other models or other graphs.

Practice exercises

  1. Ask a follow-up question on the same thread and check that the earlier messages are in the state.
  2. Add a "grade answer" node that sends the flow back to "rewrite" if the answer says "not found".

Related tutorials