Courses / Agentic AI from Scratch (Python)

Session 23 of 40

LangGraph basics: state, nodes and edges

Notes

What Is LangGraph? State, Nodes and Edges Explained With a Python Example

Agentic AI Foundations · Session 23 — A first LangGraph graph: state, nodes and edges

Before you start: what do I need before I build my first LangGraph graph?

You need the code folder for this session open in your terminal. It holds agent_graph.py, tools.py (session 21’s two tools, lookup_ticket and ask_policy), model_prompts/sort.md and model_prompts/agent.md, the copilot from session 19 (helpdesk_rag.py and search.py) with build_index.py and load_policies.py, make_tickets_db.py, data/tickets.csv with five sample tickets and data/policies/ with the five policies. Install the libraries with pip install langchain langchain-openai langchain-chroma langchain-community langchain-text-splitters langgraph, and set LLM_BASE_URL, LLM_API_KEY, LLM_MODEL and EMBED_MODEL as in earlier sessions. Two things are not in the folder, policy_index/ and tickets.db; build them with python build_index.py and python make_tickets_db.py. Recap of what this session assumes: an agent is a model that calls tools in a loop (session 20), and create_agent builds one from a model, tools and a system prompt (session 21). Have paper or a notes app ready for the Flashcards and the Model answer.

Summary: what are LangGraph state, nodes and edges?

A LangGraph graph is a workflow built from three parts: a state, which is the shared data the steps read and update; nodes, which are the steps, each an ordinary Python function; and edges, which are the links that decide which step runs next. LangGraph’s own documentation describes it as a low-level framework for stateful agents and advises it when you need explicit control over state and the order of steps. In this session you lay the Copilot out as a straight line of three nodes, receive, sort and answer, where the last one is session 21’s agent. A node returns only the keys it changes, and a reducer on a key such as steps adds each node’s list to the old one. The result is a Copilot whose steps you can name, run and read one at a time.

Key concepts: LangGraph terms explained in plain English

Term Definition
Graph A workflow made of a state, nodes and edges; here, the Copilot’s steps drawn as boxes joined by arrows.
State The one set of named values, written as a typed dictionary, that every node in the graph can read and update.
Node An ordinary Python function that takes the state and returns a dictionary of the keys it changes.
Edge A link between two nodes that says which one runs after the other.
START and END The graph’s front door, where the input enters, and its exit, where a path stops.
Reducer A rule attached to a state key that decides how a node’s update joins the old value, such as adding a list on the end.
StateGraph The LangGraph class you use to declare a graph over a state: you add nodes and edges to it.
compile() The call that checks the shape of the graph and returns the runnable graph.
stream_mode="updates" A way to run the graph so you get one item for each node that ran, holding what that node returned.

Explanations: how do state, nodes and edges build a graph?

Why turn an agent into a graph?

Failure first. A support lead asks why the Copilot gave a wrong answer about ticket T-1042. With the agent from session 21, the work happened inside one loop of model calls, and the model chose each step. There was no list of steps to check, so nobody could say where it went wrong.

Think of a recipe card with numbered steps: you can see what happens first, what happens next, and which step to blame when the dish is wrong. Or think of an assembly line where each station does one job: you can inspect the item after any station. A graph gives the Copilot that shape. LangGraph’s documentation says it fits when you need explicit control over state and the order of steps, and that a graph can mix fixed steps with steps driven by a model. In agent_graph.py the model-driven part is one node; the order around it is fixed.

What is a LangGraph graph, and what are its three parts?

Picture a railway map: stations are the steps, tracks are the links between them, and the luggage travels with the passengers. A LangGraph graph has the same three parts. The state is the shared data; the nodes are the steps; the edges say which step runs next. Nodes do the work and edges decide what runs next.

 START
   |
 [ receive ]   tidy the question
   |
 [ sort ]      one model call writes a label
   |
 [ answer ]    session 21's agent
   |
  END

 STATE carried along: question, kind, answer, steps

A graph does not make the Copilot smarter. It makes its steps visible and controllable, which is what lets later sessions add a branch, a saved checkpoint or a person’s approval at a chosen point.

What is the state, and what does a reducer do?

A shared notebook on a kitchen table is a good picture: each cook reads it, then writes only the line they changed. A baton in a relay race works too: it is handed from runner to runner and carries what they have added. The state is that notebook. In agent_graph.py it is a TypedDict, a dictionary with named, typed keys:

class CopilotState(TypedDict):
    question: str
    kind: str
    answer: str
    steps: Annotated[list, operator.add]

A plain key such as answer is overwritten when a node returns a new value for it. A key with a reducer combines the values instead. The operator.add attached to steps with Annotated means a node’s list is added to the end of the old list. Each node returns ["receive"], ["sort"] or ["answer"], and the reducer builds a record of every node that ran. Without the reducer, steps would hold only the last node’s list. Nodes do not pass values to each other; they read and write the state.

What is a node, and what does it return?

An assembly-line station does its one job and passes the item on. A cook who writes only their own line in the notebook leaves the rest of the page as it was. A node is a function in that spirit: it takes the state and returns a dictionary holding only the keys it changes. LangGraph merges that dictionary into the state, using each key’s reducer.

def receive(state):          # tidy the question
    return {"question": " ".join(state["question"].split()),
            "steps": ["receive"]}

def sort(state):             # one model call, a typed label
    label = sorter.invoke([("system", sort_text),
                           ("human", state["question"])])
    return {"kind": label.kind, "steps": ["sort"]}

def answer(state):           # session 21's agent
    result = agent.invoke({"messages": [("user", state["question"])]})
    return {"answer": result["messages"][-1].content,
            "steps": ["answer"]}

receive collapses stray spaces. sort makes one model call whose reply is typed: the label is policy, ticket or other, as in session 16’s structured output, and model_prompts/sort.md tells the model what each label means. answer calls the session 21 agent with the question and returns the text of its last message. Because a node is an ordinary function, you can call it on its own with a small dictionary to test it.

What are edges, and what does compile do?

Think of arrows on a whiteboard flowchart, or a rail timetable that says which train follows which. An edge joins two nodes: after this one, run that one. START is the front door, where the input enters the graph, and END is the exit, where a path stops. A normal edge always goes from one node to the next.

builder = StateGraph(CopilotState)
builder.add_node("receive", receive)
builder.add_node("sort", sort)
builder.add_node("answer", answer)
builder.add_edge(START, "receive")
builder.add_edge("receive", "sort")
builder.add_edge("sort", "answer")
builder.add_edge("answer", END)
graph = builder.compile()

add_node gives a step a name, add_edge joins two names. A graph must be compiled before you invoke or stream it: compile() checks the structure and returns the runnable graph. Nothing runs until you call invoke or stream on it.

How do you run the graph and read it?

Run python build_index.py and python make_tickets_db.py once, then python agent_graph.py. The script asks two questions, a policy question and a ticket question. The run function streams the graph with stream_mode="updates", which yields one item for each node that ran, and prints one line for each. Read the output for three things: the nodes appear in the order of the edges (receive, then sort, then answer); each line shows only the keys that node changed, not the whole state; and both questions take the same route, because the kind label is recorded but nothing reads it yet. Session 24 makes the label choose the path. The answer node is where the model-driven loop of session 21 runs, so it is the step that makes the most model calls.

What goes wrong with a first graph, and what does it mean for the design?

Before the design table, three situations you will meet:

  1. A wrong answer about a ticket and nobody can say which step caused it. The work happened inside one improvising loop, so there was no list of steps to read.
  2. A list of steps keeps only the last entry. The key had no reducer, so each new list replaced the old one.
  3. A node returns every key, including ones it did not change, and writes old values back over newer ones. A node should return only the keys it changes.

What these mean for the design:

What you learned The design decision Where it shows
Steps you can name can be checked one at a time Make each step a node receive, sort, answer
Nodes share one notebook Declare every key in the state CopilotState
A list needs to grow, not be replaced Give it a reducer steps with operator.add
The order is the edges Draw the order, then compile it add_edge, compile()

Basic assignment: run python agent_graph.py and, for each question, write down the nodes in the order they fired and the keys each one changed.

Project step: change one thing and see. Add a fourth node, shout, that returns the answer in capital letters, and put it between answer and END. Swap the order of receive and sort and see whether the graph still compiles. Remove operator.add from steps and print steps at the end to see what is left. The build prompt is prompts/1-write-agent-graph.md. Stop when you can say what each node returns and why the state is not replaced each time.

Flashcards: test yourself on LangGraph state, nodes and edges

Say the answer aloud before revealing it. Speaking is a different skill from reading, so practise both.

1. What are the three parts of a LangGraph graph? A state, which is the shared data the steps read and update; nodes, which are the steps, each a Python function; and edges, which are the links that decide which step runs next.
2. What does a node return? A dictionary of only the keys it changes. LangGraph merges it into the state, applying each key's reducer, so the node never has to return the whole state.
3. What is the state in agent_graph.py? A TypedDict called CopilotState with four keys: question, kind, answer and steps. Every node reads from it and writes updates to it.
4. What does a reducer do? It decides how an update joins the old value of a key. With no reducer, an update overwrites the old value; with operator.add on a list, the new list is added to the end of the old one.
5. Why does steps have operator.add? So each node's one-item list is added on the end, and steps becomes a record of every node that ran. Without it, steps would hold only the last node's list.
6. What are START and END? START is the front door, where the input enters the graph and the first node is named. END is the exit, where a path stops. Edges join them to your nodes.
7. What does compile() do? It checks the shape of the graph and returns the runnable graph. You must compile before you invoke or stream, and nothing runs until you do.
8. What does stream_mode="updates" give you? One item for each node that ran, holding what that node returned. It is how run prints one line per node, in the order the edges set.
9. What does the sort node do, and what uses its label? It makes one model call with a typed reply and writes a kind of policy, ticket or other into the state. In this session nothing reads it yet; session 24 routes on it.
10. Why does a graph help when an answer is wrong? It gives you a list of named steps, each with its own input and output. You can check them one at a time instead of searching inside one loop of model calls.

Model answer: how do I explain a LangGraph graph in an interview?

The core question this session answers: “What is a LangGraph graph, and how do you build one that runs three steps in a line?”

Four beats a teammate listens for, in this order: the three parts · the state · the nodes · wire and run. Skip any of these four and the answer is incomplete.

  1. The three parts: a state, nodes and edges.
  2. The state: typed keys, with a reducer where a list must grow.
  3. The nodes: functions that return only the keys they change.
  4. Wire and run: add the nodes and edges, compile, then stream it.

The full answer, said aloud:

(The three parts) “A graph is a workflow of three parts: a state, which is the shared data; nodes, which are the steps; and edges, which decide which step runs next.

(The state) The state is a typed dictionary of keys, and a key such as steps gets a reducer so each node’s list is added to the old one.

(The nodes) Each node is an ordinary function that takes the state and returns only the keys it changed.

(Wire and run) I add the nodes, join them with edges from START to END, call compile, and stream the graph to see each node fire.“

Missing a beat is a failure state. The follow-up question lands where you went quiet: leave out the reducer and the next question is how a list of steps gets built. Practise until the four come out without prompting, then stop talking and let the questions come.

Why this matters: why do LangGraph graphs matter at work?

In a conversation with a teammate or manager: when an assistant gives a wrong answer, the first question is which step went wrong. A graph lets you answer with a named node instead of “somewhere in the model”.

On the job: a workflow you can draw is a workflow you can test, review and change. A product owner can ask for a check at one point, an engineer can test one node alone, and a security reviewer can see what each step reads.

In the rest of this course: session 24 makes the label choose the path, session 25 saves progress between runs, session 26 pauses for a person’s approval, and later sessions put more of the Copilot in the same graph.

After this unit: what do I do after this lesson, and what comes next?

Assignment. Run python agent_graph.py and write down, for each question, the nodes in the order they fired. The brief for the project work, adding a node and removing the reducer, is the project file. Keep agent_graph.py and tools.py: the next session builds on them.

What’s next. Session 24 is about conditional routing: a routing function reads the kind label and sends each question to a policy path, a ticket path or a fallback path.

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by OpenAI, Anthropic, LangChain or any other company named in this course.