Start free

Zero to FDE / Blog / LangGraph explained: state, nodes and edges, with a 30-line example

Blog

LangGraph explained: state, nodes and edges, with a 30-line example

LangGraph is a Python and JavaScript library for building agents as graphs: you write each step as a function, connect the steps with edges, and LangGraph runs them while carrying a shared state between them. Its own docs call it “a low-level orchestration framework and runtime for long-running, stateful agents”.1

Why a graph instead of a loop

A simple AI agent is a while-loop around a model call. That works until a client asks: where did it go wrong, can a person approve this step, and can it pick up after a crash? A graph answers those questions because every step has a name and every change to the state is recorded. The docs list what you get: hand-coded and model-driven steps in one graph, saved state so a run can resume after a failure or pause, pausing for a person to inspect or edit state, memory across sessions, and streaming of events as the graph runs.1 LangGraph does not require LangChain.1

The four ideas

IdeaWhat it isIn the example
StateThe shared data the graph carries, usually a TypedDict. Each node returns only the keys it changes; by default an update overwrites the old value2question, draft, tries, log
NodeA plain function that takes the state and returns an update2write, check
EdgeRuns one node after another; START is the entry and the run ends at END2START to write, write to check
Conditional edgeA routing function reads the state and returns the next node, which is how you build branches and loops2check goes back to write until the draft cites a source

One more term: a reducer decides how updates to a key combine. With operator.add, a list key appends instead of being overwritten.2 The log key below uses it.

A tested example

This graph drafts an answer, checks that it cites a source, and retries up to three times. The model call is replaced by a plain function so you can run it with no API key. We ran it with langgraph 1.2.24 after pip install -U langgraph.1

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

class State(TypedDict):
    question: str
    draft: str
    tries: int
    log: Annotated[list[str], operator.add]  # reducer: append, don't overwrite

def write(state):
    # In a real agent this is an LLM call. Here it improves on each try.
    draft = "Refunds take 7 days." if state["tries"] == 0 else "Refunds take 7 days [policy.pdf, p2]."
    return {"draft": draft, "tries": state["tries"] + 1, "log": [f"write #{state['tries'] + 1}"]}

def check(state):
    return {"log": ["check: " + ("cited" if "[" in state["draft"] else "no source")]}

def route(state):
    if "[" in state["draft"]:
        return "done"
    return "retry" if state["tries"] < 3 else "done"

g = StateGraph(State)
g.add_node("write", write)
g.add_node("check", check)
g.add_edge(START, "write")
g.add_edge("write", "check")
g.add_conditional_edges("check", route, {"retry": "write", "done": END})
app = g.compile()

out = app.invoke({"question": "How long do refunds take?", "draft": "", "tries": 0, "log": []})
print(out["draft"])
print(out["log"])

Output:

Refunds take 7 days [policy.pdf, p2].
['write #1', 'check: no source', 'write #2', 'check: cited']

Swap the body of write for a real model call and you have the core of a RAG answerer that refuses to ship an uncited answer. The tries limit matters: LangGraph also caps runs with a recursion limit and raises GraphRecursionError when a loop runs too long.2

What to add for production

  • A checkpointer. Pass one to compile() and completed steps are saved, so a resumed run does not repeat them.2
  • Human approval. Interrupts pause the graph so a person can check the state before a risky step, such as sending an email or changing a record.1
  • Evals and traces. A graph makes each step testable on its own. Measure it with evals and watch it with tracing.

When not to use it

If the steps never change order, a plain function calling the model twice is easier to read. Reach for a graph when there are branches, loops, people in the loop or runs that must survive a restart. Our agent vs workflow guide covers that choice.

The Zero to FDE roadmap builds an agent by hand first, then rebuilds it as an agent graph, so you know what the library is doing for you. The course is self-paced and written: there are no live classes, mentors or certificate.

Zero to FDE is a self-paced 16-week course, ₹2,999 once, with a 7-day full refund. Week 1 is free, and one Week 4 lesson is free if you already write backend code. It has no live classes, no mentors and no accredited certificate.

Sources

  1. LangChain, “LangGraph overview” (LangGraph Python docs)
  2. LangChain, “Graph API: control flow” (LangGraph Python docs)

Zero to FDE is a 16-week path, for working engineers and AIML graduates, to the work Forward Deployed Engineers do: backend basics, LLMs, RAG, agents, evaluation and deployment, with a shipped deliverable every week. Week 1 is free and complete, no card needed.

Start Week 1 free

More from the blog