Velamuvi AIAcademy
LangGraph

Lesson 1 of 11 · Graphs

Why LangGraph?

Why LangGraph exists: agents need loops, branches, shared state, persistence, approvals and streaming. Its model of state, nodes and edges, and when to use it.

  • 7 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Explain what chains can't do that agents need
  • Describe LangGraph's model: shared state, nodes and edges
  • Explain how LangGraph relates to LangChain and create_agent
  • Decide when LangGraph is worth using

When a chain isn't enough

An LCEL chain (see the LangChain course) runs its steps in a fixed order, once. Many real tasks don't fit that shape:

  • Loops: draft, check, revise, check again, until it's good or you give up.
  • Branches: route a refund request one way and a repair question another, decided at run time.
  • Shared state: several steps read and update the same information: the plan, the findings so far, the number of attempts.
  • Pausing: stop for a person's approval, maybe for hours, then continue exactly where it left off.
  • Recovery: if step 7 of 10 crashes, resume from step 7, not from the start.

State, nodes and edges

A LangGraph application has three ingredients:

  • State: a dictionary-like record shared by every step, defined with a schema.
  • Nodes: Python functions that read the state and return updates to it. A node can call a model, a tool, or just compute something.
  • Edges: rules for what runs next: a fixed next node, or a conditional edge that chooses based on the state.

Here's that model in plain Python: a tiny graph runner with a write node, a check node and a conditional edge that loops back until the draft passes:

Try it yourselfPython
# A tiny graph runner, to see what LangGraph adds to a chain: shared state, nodes that update it,
# a conditional edge that decides what runs next, and a loop with a step limit.
DRAFTS = ["The Volta City 3 is a really very excellent electric bicycle for absolutely everyone in town.",
          "The Volta City 3: a light city e-bike with a 70 km range.",
          "The Volta City 3: a light city e-bike, 70 km range, 2,190 EUR."]

def write(state):                                   # stands in for a model writing a product blurb
    return {"draft": DRAFTS[state["attempts"]], "attempts": state["attempts"] + 1}

def check(state):                                   # plain code checks the draft
    problems = []
    if len(state["draft"].split()) > 15: problems.append("too long")
    if "EUR" not in state["draft"]: problems.append("no price")
    return {"problems": problems}

def route_after_check(state):                       # the conditional edge
    if not state["problems"]: return "END"
    return "END" if state["attempts"] >= 3 else "write"

NODES = {"write": write, "check": check}
EDGES = {"write": "check"}                          # fixed edge: write always goes to check
CONDITIONAL = {"check": route_after_check}          # check decides: write again, or finish

def run(state, node="write", max_steps=10):
    for _ in range(max_steps):
        state = {**state, **NODES[node](state)}     # merge the node's update into the state
        print(f"{node:<6} -> {', '.join(f'{k}={v!r}' for k, v in state.items() if k != 'draft')}")
        node = EDGES.get(node) or CONDITIONAL[node](state)
        if node == "END":
            return state
    raise RuntimeError("step limit reached")        # loops always need a limit

final = run({"attempts": 0, "problems": []})
print("Final:", final["draft"])

The state carries the attempt count and the problems found, every node sees it, and the conditional edge decides whether to loop or finish. The step limit stops a loop that never converges. LangGraph does all of this, plus saving state, pausing, streaming and running nodes in parallel.

The same shape in LangGraph

Here's a real LangGraph graph. It has no model in it at all, which is a good reminder that nodes are just functions:

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

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

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

def judge(state: State) -> dict:
    return {"verdict": "too long" if state["word_count"] > 12 else "ok"}

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

print(graph.invoke({"text": "Our e-bikes have a 5-year frame warranty."}))
Output
{'text': 'Our e-bikes have a 5-year frame warranty.', 'word_count': 7, 'verdict': 'ok'}

You describe the graph with a builder (add nodes, add edges), then compile() it into a runnable graph. START and END mark where it begins and ends. Each node returns only the keys it changes, and LangGraph merges them into the state.

LangGraph and LangChain

The two work together but are separate:

  • LangChain provides components: chat models, prompts, tools, retrievers, and create_agent.
  • LangGraph provides the runtime for multi-step, stateful work. LangChain's create_agent is itself built on LangGraph.
  • You can use LangGraph without LangChain: nodes can call any model SDK or none.

Common mistakes

Practice exercise

Write the core loop of a graph runner: run a node, merge its update, follow the edges, stop at END.

Your solutionPython
nodes = {"plan": lambda s: {"steps": 2}, "act": lambda s: {"done": s.get("done", 0) + 1}}
edges = {"plan": "act"}
def after_act(s):
    return "END" if s["done"] >= s["steps"] else "act"
conditional = {"act": after_act}

# Run the graph from "plan": call the node, merge its update into state, print the node's name,
# then pick the next node from edges (or from conditional if there is no fixed edge).
# Stop when the next node is "END". Finally print the state.
state = {}
Knowledge check

Which need is the strongest reason to use LangGraph instead of an LCEL chain?

Summary

  • Chains run once, in order; agents need loops, branches, shared state, pauses and recovery.
  • LangGraph builds applications from state, nodes (functions that update state) and edges (fixed or conditional).
  • Build with a StateGraph builder, compile, then invoke.
  • LangChain provides components; LangGraph provides the runtime, and create_agent runs on it.

Next: state, nodes and edges in depth.

Finished reading? Tick it off to track your progress.