State, Nodes, and Edges
The three building blocks of every LangGraph program - state, nodes and edges - explained slowly, with an everyday picture, step-by-step code, an LLM node, and a practice task.
What you will be able to do
- Explain state, nodes and edges in your own words, using an everyday example
- Define the state with a TypedDict, and know what TypedDict does and does not check
- Write nodes that read the state and return only what they change
- Understand exactly how LangGraph merges a node’s update into the state
- Connect nodes with START, END and add_edge, and build a graph in six steps
- Compile and invoke a graph, and watch the state change with stream()
- Write a node that calls an LLM, next to normal Python nodes
- Recognise the mistakes that fail silently: unknown keys, wrong types, changing the state in place
The idea, in plain English
Lesson 3.1 showed that a graph is boxes (nodes) and arrows (edges). This lesson answers the next question: how does information move from one box to the next?
The answer is the state - one dictionary that travels through the whole run. Every LangGraph program is built from three ideas:
State = "what do I know?" (the data). Node = "what do I do?" (a Python function). Edge = "where do I go next?" (an arrow). Most examples below are plain Python - the clearest way to see the state move. One adds a llama3 node. Everything was run with LangGraph 1.2.14.
Worked example: A greeting graph, an order-processing graph, and a graph where one node calls llama3.
1 - The input becomes the state
invoke() starts at START with the dictionary you passed in. The edge from START says that greet runs first.
graph.invoke({"name": "Chandu", "message": ""}) - the state after each step, exactly as stream(stream_mode="values") printed it.
1 - Only the items are known
The input has one field. valid_items, total and receipt do not exist yet - the nodes will add them.
graph.invoke({"items": ["python course", "notebook", "free laptop"]}) - each node fills one empty field. A real run.
Words you will see in this lesson
The words of every LangGraph program.
StateOne dictionary shared by the whole run. It holds everything the workflow knows.TypedDictA Python class that lists the keys of the state and their types.NodeA Python function: it reads the state and returns the fields it changes.EdgeAn arrow: "after this node, run that node".START / ENDTwo special names: where a run begins, and where it stops.BuilderStateGraph(State): the plan of the graph, before it can run.compile()Checks the plan and turns it into a graph you can run.invoke()Runs the graph once and returns the final state.An everyday example: the restaurant order slip
In a small restaurant, the waiter writes an order slip. The slip goes to the cook, then to the cashier:
- The waiter writes the dishes on the slip.
- The cook reads the dishes, cooks, and writes "ready".
- The cashier reads the dishes and writes the bill.
- Everyone works on the same slip, and each person writes only their own part. The cook never needs to talk to the waiter - everything is on the slip.
The order slipThe state.Waiter, cook, cashierNodes: each does one job and writes only its own part.Waiter -> cook -> cashierEdges: the order in which the slip moves.Customer walks in / bill paidSTART / END.A new customer, a new slipA new invoke(): every run has its own state.State: what the workflow knows
You describe the shape of the state with a TypedDict:
- A TypedDict lists the keys and the type of each value - question: str, answer: str.
- You still create and use the state like a normal dictionary.
- Graph = the structure (built once). State = the data (new for every run).
- TypedDict is a description, not a guard: Python does not check it while the program runs.
from typing import TypedDict
# A plain dictionary: nothing says which keys should exist
state = {"question": "What is Docker?", "answer": ""}
# A TypedDict: a description of the keys and their types
class QAState(TypedDict):
question: str # the user's question
answer: str # the answer, filled in later by a node
# You still create and use it like a normal dictionary
state: QAState = {"question": "What is Docker?", "answer": ""}
print(state["question"])Watch out: In our test a node returned {"message": 42} for a field declared as str, and LangGraph stored 42 without any error.
Nodes: functions that return changes
A node is a normal Python function with four parts:
- It receives the current state.
- It reads what it needs.
- It does its job - anything Python can do: calculate, call an LLM, an API, a database.
- It returns a dictionary with ONLY the fields it changed - not the whole state.
- Nothing to change (for example, it only logs)? Return {} or nothing. We tested both: the state passed through unchanged.
- Give each node one job and a clear name: classify_request, search_documents, generate_answer.
def greet(state: State): # 1. receives the current state
name = state["name"] # 2. reads what it needs
text = f"Hello, {name}!" # 3. does its job
return {"message": text} # 4. returns ONLY what it changedEdges, START and END
Edges decide the order of the run:
- add_edge("greet", "personalize") - after greet finishes, run personalize.
- START and END come from langgraph.graph. Every graph needs at least one edge from START.
- The order of add_node calls does not matter - only edges do. We added "two" before "one", connected START -> one -> two, and the run printed one, then two.
- A node with no edge leading to it never runs - and there is no warning. We added a node "orphan" with no edges; the graph compiled and ran without it.
Example 1 - a two-node graph
Now all three ideas together. greet writes a message; personalize reads it and makes it longer. This is the graph in the first diagram above.
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
name: str
message: str
def greet(state: State):
return {"message": f"Hello, {state['name']}!"}
def personalize(state: State):
return {"message": state["message"] + " Welcome to LangGraph."}
builder = StateGraph(State)
builder.add_node("greet", greet)
builder.add_node("personalize", personalize)
builder.add_edge(START, "greet")
builder.add_edge("greet", "personalize")
builder.add_edge("personalize", END)
graph = builder.compile()
print(graph.invoke({"name": "Chandu", "message": ""}))
print(graph.get_graph().draw_mermaid()){'name': 'Chandu', 'message': 'Hello, Chandu! Welcome to LangGraph.'}
__start__ --> greet;
greet --> personalize;
personalize --> __end__;How a change is merged into the state
After each node, LangGraph copies the returned fields into the state. Three rules:
- A field the node returned REPLACES the old value.
- A field the node did not return is KEPT. greet never mentioned name, so name stayed "Chandu".
- Lists are replaced too, not extended. items = ["a"] and a node returns {"items": ["b"]} -> items is ["b"]. To add, return state["items"] + ["b"].
- Lesson 3.5 shows MessagesState, whose messages list adds automatically - that special rule is called a reducer.
def add_b(state):
return {"items": ["b"]} # replaces the list
def add_b_correctly(state):
return {"items": state["items"] + ["b"]} # builds the new list itself
# invoke({"items": ["a"], "note": ""})
# with add_b -> {'items': ['b'], 'note': ''}
# with add_b_correctly -> {'items': ['a', 'b'], 'note': ''}Before{"name": "Chandu", "message": ""}greet returns{"message": "Hello, Chandu!"}After greet{"name": "Chandu", "message": "Hello, Chandu!"} - name kept, message replacedpersonalize returns{"message": "Hello, Chandu! Welcome to LangGraph."}After personalize{"name": "Chandu", "message": "Hello, Chandu! Welcome to LangGraph."}The six steps of every graph
Every graph in this module is built the same way. Here is the smallest one - match each line to a step:
- 1. Define the state - class State(TypedDict).
- 2. Create the builder - StateGraph(State).
- 3. Add the nodes - add_node("hello", hello).
- 4. Add the edges - add_edge(START, "hello"), add_edge("hello", END).
- 5. Compile - graph = builder.compile().
- 6. Invoke - graph.invoke({...}).
# pip install langgraph
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
# Step 1: define the state
class State(TypedDict):
message: str
# (the node)
def hello(state: State):
return {"message": "Hello from LangGraph!"}
builder = StateGraph(State) # Step 2: create the builder
builder.add_node("hello", hello) # Step 3: add the nodes
builder.add_edge(START, "hello") # Step 4: add the edges
builder.add_edge("hello", END)
graph = builder.compile() # Step 5: compile
print(graph.invoke({"message": ""})) # Step 6: invoke{'message': 'Hello from LangGraph!'}compile(): from a plan to a program
- StateGraph(State) is a builder - like an architect’s drawing. You can add rooms (nodes) and doors (edges), but you cannot live in it.
- builder.compile() checks the drawing and builds a graph you can run.
- Forgot it? builder.invoke(...) fails with AttributeError: ‘StateGraph’ object has no attribute ‘invoke’.
- The compiled graph has invoke() (run to the end), stream() (see each step) and get_graph().draw_mermaid() (print the structure).
Example 2 - an order-processing graph
A more realistic graph (the second diagram above). The input has only items. Three nodes each fill one field:
- validate_order keeps only items in the price list -> valid_items.
- calculate_total adds up the prices of valid_items -> total.
- create_receipt reads valid_items and total -> receipt.
- The nodes never call each other. calculate_total does not ask validate_order for anything - it reads the state.
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
PRICES = {"python course": 499, "agentic ai course": 999, "notebook": 50}
class OrderState(TypedDict):
items: list # what the customer wants to buy
valid_items: list # filled by validate_order
total: int # filled by calculate_total
receipt: str # filled by create_receipt
def validate_order(state: OrderState):
known = [item for item in state["items"] if item in PRICES]
print(" validate_order: kept", known)
return {"valid_items": known}
def calculate_total(state: OrderState):
total = sum(PRICES[item] for item in state["valid_items"])
print(" calculate_total:", total)
return {"total": total}
def create_receipt(state: OrderState):
lines = [f"{item}: Rs {PRICES[item]}" for item in state["valid_items"]]
lines.append(f"TOTAL: Rs {state['total']}")
return {"receipt": "\n".join(lines)}
builder = StateGraph(OrderState)
builder.add_node("validate_order", validate_order)
builder.add_node("calculate_total", calculate_total)
builder.add_node("create_receipt", create_receipt)
builder.add_edge(START, "validate_order")
builder.add_edge("validate_order", "calculate_total")
builder.add_edge("calculate_total", "create_receipt")
builder.add_edge("create_receipt", END)
graph = builder.compile()
result = graph.invoke({"items": ["python course", "notebook", "free laptop"]})
print(result["receipt"])
print("\nfull state:", result) validate_order: kept ['python course', 'notebook']
calculate_total: 549
python course: Rs 499
notebook: Rs 50
TOTAL: Rs 549
full state: {'items': ['python course', 'notebook', 'free laptop'],
'valid_items': ['python course', 'notebook'], 'total': 549,
'receipt': 'python course: Rs 499\nnotebook: Rs 50\nTOTAL: Rs 549'}Example 3 - a node that calls an LLM
A node can call a language model, just like any other Python code:
- answer_question calls llama3 and stores the reply in the state.
- count_words is plain Python: it reads what the LLM node wrote and counts the words.
- Mixing model nodes and Python nodes is normal in real agents. LangGraph treats them the same way.
from typing import TypedDict
from langchain_ollama import ChatOllama
from langgraph.graph import END, START, StateGraph
llm = ChatOllama(model="llama3", temperature=0)
class QAState(TypedDict):
question: str
answer: str
word_count: int
def answer_question(state: QAState):
# An LLM node: it calls the model and stores the reply in the state
reply = llm.invoke(f"Answer in one simple sentence: {state['question']}")
return {"answer": reply.content}
def count_words(state: QAState):
# A normal Python node: it reads what the LLM node wrote
return {"word_count": len(state["answer"].split())}
builder = StateGraph(QAState)
builder.add_node("answer_question", answer_question)
builder.add_node("count_words", count_words)
builder.add_edge(START, "answer_question")
builder.add_edge("answer_question", "count_words")
builder.add_edge("count_words", END)
graph = builder.compile()
for update in graph.stream({"question": "What is Docker?"}, stream_mode="updates"):
print(update){'answer_question': {'answer': 'Docker is a containerization platform that allows developers to package, ship, and run applications in isolated environments called containers, making it easier to develop, deploy, and manage software.'}}
{'count_words': {'word_count': 28}}Watching the state move: stream()
invoke() shows only the final state. stream() shows every step:
- stream_mode="updates" - what each node returned, with its name.
- stream_mode="values" - the whole state after each step, starting with the input.
- When a node gets a value you did not expect, stream with "updates" and look for the node that wrote it. This is the most useful debugging tool in LangGraph.
for update in graph.stream({"name": "Chandu", "message": ""}, stream_mode="updates"):
print(update)
for state in graph.stream({"name": "Chandu", "message": ""}, stream_mode="values"):
print(state)stream_mode="updates" - what each node returned
{'greet': {'message': 'Hello, Chandu!'}}
{'personalize': {'message': 'Hello, Chandu! Welcome to LangGraph.'}}
stream_mode="values" - the whole state after each step
{'name': 'Chandu', 'message': ''}
{'name': 'Chandu', 'message': 'Hello, Chandu!'}
{'name': 'Chandu', 'message': 'Hello, Chandu! Welcome to LangGraph.'}Mistakes: which ones give an error, which ones do not
Mistakes with an error are easy to fix:
- Forgot compile() -> AttributeError.
- No edge from START -> ValueError at compile(): "Graph must have an entrypoint".
- An edge to a node that does not exist -> ValueError: Found edge ending at unknown node.
- A node returns a string, not a dict -> InvalidUpdateError: Expected dict, got hi.
- Reading a key that is missing -> KeyError. If it may be missing, use state.get("question", "a default").
- The dangerous ones give NO error: an unknown key is ignored, a wrong type is stored, a change made in place (state["message"] = ...) is lost, and a node without an incoming edge never runs.
builder.invoke({"message": ""}) # forgot compile()
AttributeError: 'StateGraph' object has no attribute 'invoke'
no edge from START # at compile()
ValueError: Graph must have an entrypoint: add at least one edge from START to another node
add_edge("hello", "goodbye") # at compile()
ValueError: Found edge ending at unknown node 'goodbye'
add_node("n", f) twice # when adding
ValueError: Node ... already present.
node returns "hi" # at invoke()
InvalidUpdateError: Expected dict, got hi
node reads state["question"], not given # at invoke()
KeyError: 'question'
node returns {"greeting": "hi"} # silently ignored
{'message': ''}
node returns {"message": 42} # types not enforced
{'message': 42}
node sets state["message"] = "mutated" and returns nothing
next node saw 'original' # the change was lost
a node with no edge leading to it # compiles, never runs
no error, no warningWatch out: Return your changes; never edit the state you were given. In our run the in-place change was simply lost - no error, no warning.
Practice: build your own graph
Try it before you read the solution. Build a graph that cleans and measures a text:
- State: text (input), clean_text, word_count, report.
- Node clean: remove extra spaces and make the text lower case.
- Node count: count the words.
- Node report: write "<count> words: <clean text>".
- Tip: add_sequence([clean, count, report]) adds three nodes in a line with the edges between them. You still add START and END edges yourself.
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class TextState(TypedDict):
text: str
clean_text: str
word_count: int
report: str
def clean(state: TextState):
return {"clean_text": " ".join(state["text"].split()).lower()}
def count(state: TextState):
return {"word_count": len(state["clean_text"].split())}
def report(state: TextState):
return {"report": f"{state['word_count']} words: {state['clean_text']}"}
builder = StateGraph(TextState)
builder.add_sequence([clean, count, report]) # three nodes in a line
builder.add_edge(START, "clean")
builder.add_edge("report", END)
graph = builder.compile()
print(graph.invoke({"text": " LangGraph makes AGENTS easy "})["report"])4 words: langgraph makes agents easyCommon questions
- Why shared state? Without it every function passes all data by hand: step_a(user, question, history, ...). With state, a node reads what it needs and returns what it changed.
- Can a node be async? Yes - async def, then await graph.ainvoke(...). invoke() on a graph with an async node failed with TypeError: No synchronous function provided.
- Must the input contain every field? No. The order example passed only items. But reading a missing key with state["key"] fails.
- What does invoke() return? The whole final state. Input keys that are not in the TypedDict are dropped.
LangGraph basics at a glance
StateGraphThe builder, made from a state description.
StateGraph(State)
TypedDictDescribes the state’s keys and types - not checked at run time.
class State(TypedDict): message: str
add_nodeA name and the function that does the work.
builder.add_node("greet", greet)add_edgeAlways run this node next.
builder.add_edge("greet", "personalize")START / ENDWhere a run enters and where it stops.
from langgraph.graph import START, END
compileCheck the structure, build the runnable graph.
graph = builder.compile()
invokeRun to END; returns the whole final state.
graph.invoke({"name": "Chandu"})streamEach node’s change, or the state after each step.
graph.stream(x, stream_mode="updates")
add_sequenceSeveral nodes in a line, edges included.
builder.add_sequence([clean, count, report])
ainvokeRun a graph that has async nodes.
await graph.ainvoke({...})Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Make greet say "Hi, Chandu!" and run the graph again.”
“Add course: str to the state and make the final message "Hello, Chandu! Welcome to the Agentic AI course."”
“In the order graph, add an apply_discount node between calculate_total and create_receipt that takes 10% off totals above Rs 500.”
“In the LLM example, ask "What is Kubernetes?" and add a third node that makes the answer upper case.”
“Return {"greeting": "hi"} from a node, then return "hi". Which mistake would you notice? Which one would you miss?”
“Run the order graph with stream_mode="values" and see the empty fields fill in one by one.”
What usually goes wrong
The builder only describes the graph; only the compiled graph can run.
✗ builder.invoke({"message": ""})✓ graph = builder.compile()
graph.invoke({"message": ""})compile() refuses with "Graph must have an entrypoint".
✗ builder.add_edge("hello", END)✓ builder.add_edge(START, "hello")
builder.add_edge("hello", END)It is dropped without an error. When a change seems to disappear, compare the key with the TypedDict.
✗ return {"greeting": "Hello"} # State has message, not greeting✓ return {"message": "Hello"}The change is lost - the next node sees the old value.
✗ def greet(state):
state["message"] = "Hello"✓ def greet(state):
return {"message": "Hello"}A returned list replaces the old one. Build the full new list in the node.
✗ return {"items": ["b"]}✓ return {"items": state["items"] + ["b"]}A do_everything node hides the workflow inside one function. Split it, so each step is a node with its own name.
✗ builder.add_node("process", process_everything)✓ builder.add_sequence([classify, search, validate, generate])Key points
- State = the shared data of one run. Graph = the structure, built once.
- Describe the state with a TypedDict - it helps readers, but is not checked when the program runs.
- A node is a function: it reads the state and returns only the fields it changes.
- LangGraph copies each returned field into the state; fields not returned stay; a returned field replaces the old value (lists too).
- Edges decide the order; every graph needs an edge from START, and a node with no edge leading to it never runs.
- Six steps: state, StateGraph, add_node, add_edge, compile, invoke.
- stream(stream_mode="updates" or "values") shows the state changing step by step.
- Unknown keys are ignored and in-place changes are lost - with no error.
Quick check before you move on
Quiz
- 1.
A node returns {"greeting": "hi"} but the state only has message. What happens?
- 2.
A node sets state["message"] = "x" and returns nothing. What does the next node see?
- 3.
The state has items = ["a"]. A node returns {"items": ["b"]}. What is items now?
- 4.
You added a node but it never runs, and there is no error. What is the most likely cause?
- 5.
When is a missing START edge reported?
- 6.
What is the difference between stream_mode="updates" and "values"?
Interview questions
What is StateGraph?
The LangGraph builder for a workflow with shared state. You give it a state schema, add nodes and edges, then compile it into a runnable graph that you invoke or stream.
What is the difference between a node and an edge?
A node does work - a function that reads the state and returns changes. An edge controls the flow - which node runs after which.
How does data flow between nodes?
Each node receives the current state and returns a partial update. LangGraph merges it - returned fields replace old values, others are kept - and passes the merged state along the edges to the next node.
Why does LangGraph use shared state?
Nodes read what they need and write what they change, instead of passing every value through every function. This matters most once a graph branches and loops.
What happens at compile time?
The structure is checked - an entry from START, no edges to unknown nodes - and a runnable CompiledStateGraph is returned.
Which state mistakes do not raise errors, and how do you find them?
Returning unknown keys (ignored), wrong types (stored as given), and changing the state in place (lost). Stream the run with stream_mode="updates" to see what each node actually returned.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...