Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 6 steps

Agents with LangChain and LangGraph
  1. 1
    What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  2. 2
    Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  3. 3
    LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  4. 4
    Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  5. 5
    Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  6. 6
    A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

Learning path: Agents with LangChain and LangGraph · Step 2 of 6

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Spot the three gaps in a linear chain: no branch, no retry, no pause
  • Draw the same flow as a graph with conditional edges and a retry loop
  • See how one shared state lets a retry remember what changed
  • Decide when a chain is still fine and when you need a graph

Before you start

  • What LangChain Is For, and When to Skip It
  • Python dictionaries and functions

A simple chain of steps is the first thing most people build with an LLM. It also breaks down quickly, and that's why so many agent builders move to a graph. We'll see exactly why with one small example, a refund assistant, built three ways: as a chain, as plain Python, and as a LangGraph graph.

In short: a chain always picks the same next step. A graph can choose.

A train track and a road map

Think about a train. It goes forward only, station after station. Even at a junction it can't turn off, and it can't go back. Now think about a car on a road map. At a junction it can turn. It can go round the block and come back to the same street. And it can stop at a checkpoint and wait until someone lifts the bar.

A chain is the train track. A graph is the road map.

Meet the refund assistant

A customer writes: I want a refund for my order. The order total is $150. The assistant has three jobs: work out what kind of message this is, look up the refund policy, and write the reply. The policy is three short lines, and all three versions share the same small steps in steps.py:

"""The small steps every version shares. Each step reads the state and returns what it changes."""

POLICY = [
    "Refunds are handled by the billing team.",
    "Refunds are allowed within 30 days of purchase.",
    "Refunds above 100 dollars need a manager's approval.",
]


def classify(state):
    intent = "refund" if "refund" in state["question"].lower() else "other"
    return {"intent": intent}


def retrieve(state):
    return {"docs": POLICY[: state["top_k"]]}


def write_reply(state):
    return {"reply": " ".join(state["docs"])}


def grade(state):
    good = "30 days" in state["reply"]
    return {"good": good, "top_k": state["top_k"] + (0 if good else 1)}


def general_answer(state):
    return {"reply": "Please contact support and we will help."}


def ask_human(state):
    return {"approved": state["reviewer_says_yes"]}


def new_state(question, amount):
    return {"question": question, "amount": amount, "intent": "", "top_k": 1,
            "docs": [], "reply": "", "good": False, "approved": False,
            "reviewer_says_yes": True}

retrieve takes the first top_k policy lines; with top_k at 1, that's only the billing-team line. grade checks the reply for the words "30 days", and if they're missing it sets good to False and raises top_k by one, so the next retrieve fetches more. new_state starts top_k at 1, and reviewer_says_yes stands in for the person who approves. Each step reads the state and returns only what it changes.

The chain: one pass, no way back

"""A chain: classify -> retrieve -> reply. One pass, no way back."""
from steps import classify, retrieve, write_reply, new_state


def run_chain(state):
    for step in (classify, retrieve, write_reply):
        state.update(step(state))
    return state


if __name__ == "__main__":
    final = run_chain(new_state("I want a refund for my order", 150))
    print(final["reply"])
Refunds are handled by the billing team.

The state rides down one line, in one direction, and each step runs exactly once. That one line has three gaps:

  1. No branch. Ask the chain What are your opening hours? and it still answers "Refunds are handled by the billing team." Every message takes the same path.
  2. No retry. The reply is missing the 30-day window, and there's no way to go back one step and fetch more.
  3. No pause. A $150 refund goes straight out, and approved stays False. Nobody was asked.

The same flow as a graph

Draw the same flow with a box for every step and arrows that can choose where to go.

The refund assistant as a graph classifyretrievewrite_reply gradeask_humangeneral_answer ENDEND refund other retry (not good) approve (> 100) done
Branch, loop and pause are arrows in the flow itself, not extra code around it.
  • After classify, two arrows: refund goes to retrieve, anything else to a general answer. That's the branch.
  • After grade, if the reply is weak, an arrow goes back to retrieve. That's the retry loop.
  • If the reply is good and the amount is over 100, the arrow goes to ask_human. That's the checkpoint.

One shared state

How does a step know what happened before it? Through state. On the first pass, classify writes intent "refund", retrieve writes one policy line, write_reply turns it into the reply, and grade says good is False and moves top_k from 1 to 2. So the graph goes round again: retrieve now fetches two lines, the reply includes the 30-day window, and grade says True. Then ask_human writes approved True. The retry works because the state remembers that top_k went from 1 to 2.

Plain Python: the flow as if and while

Can't we do all this in plain Python? Yes:

"""The same flow with plain Python: if, while, and a human check."""
from steps import (classify, retrieve, write_reply, grade,
                   general_answer, ask_human, new_state)


def run_plain(state):
    state.update(classify(state))
    if state["intent"] != "refund":
        state.update(general_answer(state))
        return state
    while True:
        state.update(retrieve(state))
        state.update(write_reply(state))
        state.update(grade(state))
        if state["good"]:
            break
    if state["amount"] > 100:
        state.update(ask_human(state))
    return state

The if is the branch, the while is the retry (it goes round twice before it breaks out), and the last if is the approval. It works. But the flow is hidden inside if and while. You can't draw it, and you can't easily pause it halfway.

03_graph.py: the flow as nodes and edges

"""The same flow as a graph: nodes, edges and one shared state."""
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from steps import (classify, retrieve, write_reply, grade,
                   general_answer, ask_human, new_state)


class State(TypedDict):
    question: str
    amount: int
    intent: str
    top_k: int
    docs: list
    reply: str
    good: bool
    approved: bool
    reviewer_says_yes: bool


def after_classify(state):
    return state["intent"]


def after_grade(state):
    if not state["good"]:
        return "retry"
    return "approve" if state["amount"] > 100 else "done"


builder = StateGraph(State)
for step in (classify, retrieve, write_reply, grade, general_answer, ask_human):
    builder.add_node(step.__name__, step)
builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", after_classify,
                              {"refund": "retrieve", "other": "general_answer"})
builder.add_edge("retrieve", "write_reply")
builder.add_edge("write_reply", "grade")
builder.add_conditional_edges("grade", after_grade,
                              {"retry": "retrieve", "approve": "ask_human", "done": END})
builder.add_edge("general_answer", END)
builder.add_edge("ask_human", END)
graph = builder.compile()

if __name__ == "__main__":
    final = graph.invoke(new_state("I want a refund for my order", 150))
    print(final["reply"], final["approved"])
  • State is a TypedDict: a dictionary with named slots.
  • after_classify and after_grade are small signpost functions. They return the name of the road to take.
  • StateGraph(State) creates the builder, and each step is added as a node under its own name.
  • add_conditional_edges turns a signpost's answer into an arrow: "retry" goes back to retrieve, "approve" to ask_human, "done" to the end.
  • compile() checks the wiring and gives us a graph we can run.
Refunds are handled by the billing team. Refunds are allowed within 30 days of purchase. True

The reply now includes the 30-day window, and approved is True: the same answer as the plain version, and the project's three tests pass. Run the same refund for $50, and the graph goes round the retry loop as before, then stops after grade: ask_human never runs and approved is False. Ask about opening hours, and classify says "other", so the graph goes to the general answer: Please contact support and we will help. Same graph each time, and the arrows chose the path.

When is a chain still fine?

A chain is fine when...A graph helps when...
The order is always the sameThe next step depends on the result
Each step runs onceThe flow may go round again
Nobody is in the loopThe flow must pause for approval

Summarise a text and then translate it: that's a perfect chain. The refund assistant needs a graph. Start with a chain, and move to a graph the day you need a branch, a loop or a pause.

Common mistakes

  • Forcing branching logic into a chain. The opening-hours question got a refund answer because every message took the same path.
  • A retry without memory. Going round again only helps if something changed; here the state carries top_k from 1 to 2.
  • Hiding the flow in nested if and while. It runs, but nobody can draw it, test one path, or pause it halfway.
  • Reaching for a graph too early. A fixed two-step job is simpler as a chain.

Quick recap

  • A chain goes one way: no branch, no retry, no pause.
  • A graph has nodes, arrows that choose, and one shared state that remembers what happened.
  • Plain if and while can do the same job, but the flow stays hidden.

Try it yourself

Run 03_graph.py, then change the amount in the last line to 50 and run it again: which node no longer runs? Next, see each piece of a graph up close in LangGraph Nodes, Edges and State.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Agents with LangChain and LangGraph · step 2 of 6

Previous
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
Next post
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)

A refund under 50 is approved by itself; 120 must wait for a person, maybe until tomorrow. interrupt pauses the graph and returns a question, SqliteSaver keeps the state in refunds.db after the program ends, and a brand new process resumes thread t-big with Command(resume="approve") at ask_human, not at the start.

On this page

  • A train track and a road map
  • Meet the refund assistant
  • The chain: one pass, no way back
  • The same flow as a graph
  • One shared state
  • Plain Python: the flow as if and while
  • 03_graph.py: the flow as nodes and edges
  • When is a chain still fine?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.