3  The Smallest Graph

Before agents, tools, loops, or language models, LangGraph is one idea:

A node is just a function. State goes in, a state update comes out, and the runtime merges the update back in for you.

That is the whole engine. Branching, retries, human approval, and streaming are all built on top of it. So we start with the smallest program that demonstrates it — one state, one node, no LLM. The answer is hard-coded; what we watch is the machine turning over.

3.1 What we’re building

A “graph” with one step. It takes a question and produces an answer — one node, two edges:

flowchart LR
    START(["START"]) --> answer("answer") --> END(["END"])

Wiring even this much means meeting the three objects every later chapter uses: the state, the node, and the edges that connect them.

3.2 The State

The state is the one shared object flowing through the graph. Each node receives it and may return an update. You describe its shape with a TypedDict — a plain dictionary whose keys and types are declared up front.

from typing import NotRequired, TypedDict


class State(TypedDict):
    question: str              # input:  the caller provides this
1    answer: NotRequired[str]   # output: a node fills this in
1
answer is produced by a node later, so it is NotRequired. The schema lists every channel the graph may use, not what the input must supply.

At runtime a State is an ordinary Python dict. LangGraph reads its keys to build the graph’s state channels. The annotations are for your editor and your future self, and are never checked (the Challenge has you break them).

NoteDeep Dive: why a dict and not an object?

Because the state is plain data, the runtime can merge partial updates into it knowing nothing about your program — and later, with a checkpointer, snapshot and persist it too. (TypedDict is the lowest-ceremony declaration; LangGraph also accepts dataclasses and Pydantic models.) Keep the state boring and the framework can do a lot with it.

3.3 The Node

A node is a function. Its input is the current state; its output is a dict describing the changes it wants to make.

def answer_node(state: State) -> dict:
    question = state["question"]

    # Hard-coded for now; a real LLM replaces this in Part II.
    reply = f"You asked: “{question}”. (This answer is hard-coded.)"

    # Return only the fields we want to change, not the whole state.
1    return {"answer": reply}
1
The rule: a node returns a state update, not a new state. Only answer was touched, so the update says nothing about question.

NoteDeep Dive: a node can return an empty update

return {} is legal, and so is return None. A node that returns an empty update writes nothing — useful when it runs only for a side effect (logging, an external API call) or is a placeholder to fill in later. Chapter 4 opens with such a node. More dangerous: an update naming a key the State never declared is dropped with no error. Misspell answer and nothing is written, and nothing complains. Side effects bring their own rule once we add retries (Chapter 21).

3.4 Wiring it up

Now assemble the parts with a StateGraph builder: register the node, then add the edges. START and END are built-in nodes standing for the graph’s entrance and exit.

from langgraph.graph import StateGraph, START, END

builder = StateGraph(State)          # this graph's state has shape `State`
builder.add_node("answer", answer_node)

builder.add_edge(START, "answer")    # enter → run `answer`
builder.add_edge("answer", END)      # then → done

graph = builder.compile()            # turn the design into a runnable graph

flowchart TD
    START(["START"]) --> answer("answer") --> END(["END"])

Two phases: add_node and add_edge describe the graph, and compile() freezes that description into something you can execute. Everything before compile() is design time; everything after is run time.

3.5 Running it

invoke runs the graph to completion from an initial state and returns the final one.

if __name__ == "__main__":
    result = graph.invoke({"question": "How do I configure Kafka in Spring Boot?"})

    print("final state:", result)
    print("answer:", result["answer"])

Run it and you’ll see:

final state: {'question': 'How do I configure Kafka in Spring Boot?',
              'answer': 'You asked: “How do I configure Kafka in Spring Boot?”. (This answer is hard-coded.)'}
answer: You asked: “How do I configure Kafka in Spring Boot?”. (This answer is hard-coded.)

What came back is the whole state. The node wrote one field and the runtime kept the rest.

TipTry it: add a second field and watch the merge

Add lang: NotRequired[str] to State and have answer_node return {"answer": reply, "lang": "en"}. Re-run: both fields land in the final state, question untouched.

3.6 The same shape elsewhere

If you have written a Redux reducer or an Elm update, answer_node needs no introduction: you are handed the state, you return a value, and something else decides what the state becomes. Your function never reaches into the store and sets a field.

One difference matters, and Chapter 10 collects on it. A Redux reducer returns the whole next state; a node returns only the keys it touched, and the merge happens per key. That is why the delta is a partial dict. It is also why one question needs a chapter of its own: what happens when two writers touch one key?

3.7 What we learned

  • A node is a function from state to a partial update: return the delta, never mutate the state, and let the runtime merge it back.
  • Build, then compile, then run are three distinct phases.

Here everything happened in one node, so the merge had nothing to compete with. In the next chapter the graph becomes a three-node line, answer becomes generate, and the state accumulates as it flows down it.

New pieces in this chapter

Piece Usage
Type
TypedDict Declares the state’s shape: a plain dict with typed keys. class State(TypedDict): question: str; the annotations aren’t checked at runtime
NotRequired Marks a state key the initial input need not supply. answer: NotRequired[str]; the schema lists channels the graph may use
StateGraph Builder for a graph over a typed state schema. StateGraph(State); build-time only — nothing runs until compile()
Value
START Built-in node standing for the graph’s entrance. builder.add_edge(START, "answer")
END Built-in node standing for the graph’s exit. builder.add_edge("answer", END)
API
StateGraph.add_node() Register a node function under a name. builder.add_node("answer", answer_node); the function returns a partial update, not a new state
StateGraph.add_edge() Wire one node to the next. builder.add_edge(START, "answer"); edges only describe the flow — still design time
StateGraph.compile() Freeze the design into a runnable graph. graph = builder.compile(); the line where design time ends and run time begins
graph.invoke() Run the compiled graph to completion from an initial state. graph.invoke({"question": …}); returns the whole final state, not just the fields you changed

Code in this chapter

File What it runs
code/ch01_minimal_graph.py One state, one node, a hard-coded answer – the machine turning over: state in, update out, runtime merges.

Challenge

Bronze feeds the graph three bad inputs and watches what TypedDict lets through; Silver swaps in a Pydantic model to get some of the checks back.

🥉 Bronze — find the holes in TypedDict

Invoke the graph three ways: with an extra key the schema never declared, with question set to an int, and with question missing entirely. Predict each outcome first, then run it.

You get three different failure modes, none of them the one a typed language would give you: one input is silently dropped, one runs with the wrong type, and one fails later than you’d think — only because a node reads the missing key.

office hours Worked solution with tests: code/answers/ch01_typeddict_no_validation.py.

🥈 Silver — opt into validation

Re-declare State as a Pydantic BaseModel (question: str, answer: str | None = None) and rerun the same three bad inputs. What did you have to change inside the node to read the state?

Now the wrong type and the missing key are rejected at invoke(), before any node runs. But Pydantic validates the state handed to a node, not the update a node returns. Have a node return {"answer": 12345} into the str | None field and the integer lands unchanged — this one-node graph has no later node to receive it, and the final output is not re-validated. Add a second node after it and that node’s input is rebuilt from the schema, so the bad answer is rejected there. Chapter 14 shows why.

office hours Worked solution with tests: code/answers/ch01_pydantic_state.py.