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 3 of 6

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.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Define a graph's state as a TypedDict and write nodes that return only what they change
  • Wire plain edges and a conditional edge whose router names the next node
  • Put a model call inside a node and guard its answer
  • Choose between invoke, stream values and stream updates, and use a reducer to append instead of overwrite

Before you start

  • Why Chains Break: The Case for Graphs
  • Python dictionaries and type hints

A LangGraph graph has three parts: state, nodes and edges. Nodes do the work, edges pick who works next, and the state carries everything. In this article we build two small graphs: a refund-assistant skeleton with plain functions, then a help desk whose nodes call a model. Both run without an API key.

If you haven't seen why we'd want a graph at all, start with Why Chains Break.

A relay race with a baton

Picture a relay race. A customer message goes onto the baton, and the baton reaches the first runner, classify. Classify reads the message and writes the intent on the baton: refund. The baton comes to the coach, who reads the intent and sends it down the refund lane, where the refund runner writes the reply. Then it crosses the finish line, carrying a little log with one note from each runner.

A runner is a node. The baton is the state. The coach, who makes a choice, is a conditional edge.

The refund skeleton graph STARTclassifyroute refundinfoEND "refund""info" state: message | intent | reply | log (rides along every arrow)
Boxes are nodes, arrows are edges. route only reads the state and names the next node; it is not a node itself.

The state: a TypedDict

"""Refund assistant skeleton as a LangGraph graph. Plain functions, no LLM."""
import operator
from typing import Annotated, TypedDict

from langgraph.graph import END, START, StateGraph


class SupportState(TypedDict):
    message: str
    intent: str
    reply: str
    log: Annotated[list[str], operator.add]

SupportState is a TypedDict: just a dictionary with named slots. message is the customer's text and comes in at the start. intent and reply are empty for now; the nodes fill them in. log is a list with something extra wrapped around it. We'll come back to that at the end; for now, remember that this list only grows.

A node is a plain function

def classify(state: SupportState) -> dict:
    text = state["message"].lower()
    intent = "refund" if "refund" in text or "money back" in text else "info"
    return {"intent": intent, "log": ["classify -> " + intent]}


def refund(state: SupportState) -> dict:
    return {"reply": "Refund started. Expect an email soon.", "log": ["refund ran"]}


def info(state: SupportState) -> dict:
    return {"reply": "Our policy and hours are on the help page.", "log": ["info ran"]}


def route(state: SupportState) -> str:
    return state["intent"]

classify receives the whole state. For I want my money back for order 1042, it finds "money back", so the intent is refund. Look at what it returns: only the intent and one log note. The message stays where it is. A node gives back only what it changed.

route is different. It never changes the state; it only reads it and names the next step. That's the coach.

The code lays the track

builder = StateGraph(SupportState)
builder.add_node("classify", classify)
builder.add_node("refund", refund)
builder.add_node("info", info)

builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", route, {"refund": "refund", "info": "info"})
builder.add_edge("refund", END)
builder.add_edge("info", END)

graph = builder.compile()

INPUTS = ["I want my money back for order 1042", "What are your opening hours?"]

if __name__ == "__main__":
    for text in INPUTS:
        print("Customer:", text)
        for update in graph.stream({"message": text, "log": []}, stream_mode="updates"):
            print("  ", update)
        print()
  • StateGraph(SupportState) makes an empty graph and tells it which state to use.
  • add_node gives each function a name on the graph.
  • add_edge is a plain edge: after this one, always that one. START goes to classify; refund and info go to END.
  • add_conditional_edges("classify", route, {...}): after classify, call route and follow its answer.
  • compile() turns the builder into a graph you can run.
Customer: I want my money back for order 1042
   {'classify': {'intent': 'refund', 'log': ['classify -> refund']}}
   {'refund': {'reply': 'Refund started. Expect an email soon.', 'log': ['refund ran']}}

Customer: What are your opening hours?
   {'classify': {'intent': 'info', 'log': ['classify -> info']}}
   {'info': {'reply': 'Our policy and hours are on the help page.', 'log': ['info ran']}}

Same graph, two messages, two paths. For the first message the info node never runs; for the second, refund never runs. Each line is one node, handing back only what it changed.

Overwrite or append: the reducer

When a node returns a value, the field decides what happens to it. By default, a new value replaces the old one. Classify returned "refund", so the intent slot now holds refund; if a later node returned a new intent, it would replace this one. reply works the same way.

The log is different. Annotated[list[str], operator.add] changes the rule for that one field: new items are added to the list. Classify adds its note, then the refund node adds another, and both are still there. The project's tests check exactly that: the final log holds "classify -> refund" and then "refund ran".

Your first LangGraph with a model inside

Now a help desk where the nodes call a model. Picture a shared notebook passed from desk to desk: the sorter writes the category, a fork in the hallway decides where the notebook goes, the answer desk writes the reply, and a spam message goes straight to the out tray. Notebook is state, desk is node, fork is conditional edge.

"""First LangGraph: sort a customer message, then answer it."""
from typing import TypedDict

from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langgraph.graph import END, START, StateGraph

LABELS = {"billing", "howto", "spam"}


class TicketState(TypedDict, total=False):
    message: str
    category: str
    reply: str


class TestModel(FakeListChatModel):
    calls: int = 0

    def _call(self, *args, **kwargs):
        self.calls += 1
        return super()._call(*args, **kwargs)


def get_model(replies):
    # Test model: gives back scripted replies.
    # With a key, return a real chat model here.
    return TestModel(responses=replies)

total=False means a slot may stay empty. TestModel gives back scripted replies one after another and counts its calls, so no key is needed. get_model is the only place that picks the model; with a key you'd return a real chat model there and nothing else changes.

def build_graph(model):
    def classify(state: TicketState) -> dict:
        prompt = ("Label this as billing, howto or spam. One word.\n"
                  + state["message"])
        label = model.invoke(prompt).content.strip().lower()
        return {"category": label if label in LABELS else "howto"}

    def answer(state: TicketState) -> dict:
        prompt = (f"Write a short {state['category']} reply "
                  f"to: {state['message']}")
        return {"reply": model.invoke(prompt).content}

    def route(state: TicketState) -> str:
        return END if state["category"] == "spam" else "answer"

    builder = StateGraph(TicketState)
    builder.add_node("classify", classify)
    builder.add_node("answer", answer)
    builder.add_edge(START, "classify")
    builder.add_conditional_edges("classify", route, ["answer", END])
    builder.add_edge("answer", END)
    return builder.compile()

classify sends a prompt and gets one word back. What if the model says something strange? The word is checked against LABELS, and anything unknown becomes "howto", so a strange answer never breaks the graph. route returns END for spam and "answer" for everything else.

Three messages, three paths

Customer: I was charged twice
  state: {'message': 'I was charged twice'}
  state: {'message': 'I was charged twice', 'category': 'billing'}
  state: {'message': 'I was charged twice', 'category': 'billing', 'reply': 'Sorry, our billing team will fix it.'}
  model calls: 2

Customer: How do I reset my password?
  state: {'message': 'How do I reset my password?'}
  state: {'message': 'How do I reset my password?', 'category': 'howto'}
  state: {'message': 'How do I reset my password?', 'category': 'howto', 'reply': 'Open Settings, then Security, then Reset.'}
  model calls: 2

Customer: WIN a free phone, click now
  state: {'message': 'WIN a free phone, click now'}
  state: {'message': 'WIN a free phone, click now', 'category': 'spam'}
  model calls: 1

The billing and password messages take the same shape: the state grows from one slot to two to three, with two model calls. The spam message stops after the category. The answer node never runs, so it costs one model call instead of two.

Three ways to read a run

CallWhat you getFor "I was charged twice"
graph.invoke(...)Only the final stateOne dictionary with message, category and reply
graph.stream(..., stream_mode="values")The whole state after each stepThree snapshots (above)
graph.stream(..., stream_mode="updates")Only what each node changedclassify: category; answer: reply

Answer only, every snapshot, or who changed what: pick the one you need. The refund skeleton used updates; the help desk used values.

Common mistakes

  • Returning the whole state from a node. Return only the keys you changed; the graph merges them in.
  • Doing work in the router. A routing function reads the state and names the next node. It shouldn't change anything.
  • Trusting a model's label blindly. Check it against the allowed set, with a safe default, like LABELS and "howto".
  • Expecting a list to grow without a reducer. Without Annotated[..., operator.add], each node's list replaces the last one.
  • Picking the model in several places. Keep it in one function, like get_model, so tests and production differ in one line.

Quick recap

PartIn codeJob
Stateclass SupportState(TypedDict)The baton that rides along every arrow
Nodeadd_node("classify", classify)Reads the state, returns only what it changed
Plain edgeadd_edge("refund", END)After this one, always that one
Conditional edgeadd_conditional_edges("classify", route, ...)The router names the next node
ReducerAnnotated[list[str], operator.add]Append instead of overwrite

Try it yourself

Add a fourth message to SCRIPT in the help desk, for example a scripted label the model shouldn't use, such as "urgent", and predict the path before you run it. Then make the graph pause for a person before it acts: see Human-in-the-Loop and Checkpointing.

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 3 of 6

Previous
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
Next post
Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)

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.

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.

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 relay race with a baton
  • The state: a TypedDict
  • A node is a plain function
  • The code lays the track
  • Overwrite or append: the reducer
  • Your first LangGraph with a model inside
  • Three messages, three paths
  • Three ways to read a run
  • 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.