Your First Graph: State, Nodes and Edges

An AI agent is a program that runs a few steps in some order: call the model, run a tool, call the model again, stop. When you write it as a loop, that order lives in while, if and break statements. LangGraph lets you write the same program as a graph instead: the steps become named functions, the order between them becomes connections you declare, and the data they share becomes one typed structure. This page explains those three parts (state, nodes and edges) and how a graph is compiled and run.

The same agent, drawn as a graph

Here is the agent loop you may already know, written in plain Python. The helper functions stand for the model call and the tool runner; what matters is the shape of the control flow.

An agent as a hand-written loop
messages = [{"role": "user", "content": question}]

while True:
    reply = call_model(messages, tools)
    messages.append(reply)
    if not reply.tool_calls:
        break
    for call in reply.tool_calls:
        messages.append(run_tool(call))

print(messages[-1].content)

This works, but the structure of the program is spread across its syntax. To find out which steps exist, you read the whole body. To find out when it stops, you look for the break. The data the steps share is a local variable that anything in the loop can change. Adding a step, say a check of the question before the first model call, means editing the middle of the loop and making sure every path still reaches it.

A graph states the same program as data. Each step is a node, a box with a name. The order between steps is an edge, an arrow from one node to the next. The values the steps share live in one state that every node reads and updates. The loop above becomes two nodes and four arrows, counting the one in from START and the one out to END:

  • START
  • call model
    A node

    One step of the program: a function that reads the state and returns what it changed.

  • run tools
    Another node

    Runs the tool calls of the last model reply and adds their results to the state.

  • END
  • START to call model
  • call model to run tools: asked for tools
  • run tools to call model: results back
  • call model to END: no tool calls

Nothing about the behaviour changed: the program still calls the model, runs tools while the model asks for them, and stops when it does not. What changed is that every step has a name, every possible next step is a declared arrow, and the shared data has one declared shape. A library can now check the structure before anything runs, draw it, run it step by step and report what each step did. The loop could do none of that, because its structure only existed as code to be executed.

The rest of this page builds a graph from the ground up with arrows that are always followed. Arrows that choose between two destinations, like the one leaving call model here, are a separate feature that builds on these.

True or false?

Turning a loop into a graph changes what the agent does.

False. The steps and their order stay the same. The graph only makes them explicit: named steps, declared connections and one declared state.

In a graph, you can list every step a program may take without running it.

True. The nodes and edges are declared data, so the full structure is known before the first step runs. In a loop it is hidden in the control statements.

What LangGraph is

LangGraph is a Python library for exactly this: you define a program as a graph of shared state, nodes and edges, and its runtime runs that graph. Its documentation calls it "a low-level orchestration framework and runtime for long-running, stateful agents". Low-level means it gives you the building blocks and does not decide your prompts or the shape of your agent. A node can call a model, or it can be any other Python code, so one graph can mix fixed steps with steps a model drives.

LangGraph is made by the company behind LangChain, a library of integrations for models and tools, but it does not require LangChain. You install it on its own with pip install -U langgraph. Many graphs still use a LangChain chat model inside a node, because that is a convenient way to talk to a model provider, but the graph itself does not depend on it.

There is also a quicker way to get an agent: LangChain's create_agent builds the model-and-tools loop for you, and it runs on LangGraph underneath. The choice between the two comes down to how much of the flow you want to own.

OptionWhat you getChoose it when
A ready-made agent (create_agent)The standard loop of a model and tools, built for youThe standard loop is what you need and you want a fast start
Your own LangGraph graphEvery node, edge and state key, written by youYou need explicit control over the state and the order of steps

True or false?

To use LangGraph you must also build your program with LangChain.

False. LangGraph works on its own. LangChain is optional, often used only for its chat model integrations inside nodes.

A node in a LangGraph graph does not have to call a language model.

True. A node is an ordinary function. It can call a model, a database or nothing at all.

State: the data every node shares

A graph has exactly one state: the shared data that its nodes read and update as the run goes on. You declare its shape up front in a state schema, usually a TypedDict. Each key of the schema is a slot that any node may read and any node may write.

Take a small help-desk graph with no model in it at all. It receives a question, decides its topic, and writes an answer. Its state needs three keys:

A state schema
from typing_extensions import TypedDict


class State(TypedDict):
    question: str
    topic: str
    answer: str

The schema is a contract more than a container. It tells every node which keys exist and what type each holds, and it tells the library which keys it should track between steps. By default the same schema also describes the input the graph accepts and the output it returns.

A TypedDict is the common choice and a fast one. A dataclass works when you want default values, and a Pydantic model when you want the input validated. That validation applies only to the input entering the first node, not to every later update.

Nodes: functions that return what they change

A node is a plain Python function. LangGraph calls it with the current state as its first argument, and the function returns a dictionary of only the keys it wants to change. That dictionary is called an update. Here are the two nodes of the help-desk graph:

Two nodes
def classify(state: State) -> dict:
    text = state["question"].lower()
    topic = "billing" if "invoice" in text else "general"
    return {"topic": topic}


def answer(state: State) -> dict:
    if state["topic"] == "billing":
        return {"answer": "Invoices are under Account, then Billing."}
    return {"answer": "A member of the team will reply soon."}

Neither node returns the whole state. LangGraph takes each update and merges it into the state: every key in the update replaces the old value, and every key left out keeps the value it had. So classify does not need to know that answer exists, and adding a new key to the schema later does not break either node.

How one update is merged
KeyState beforeUpdate from classifyState after
question"Where is my invoice?"(not returned)"Where is my invoice?"
topic(not set)"billing""billing"
answer(not set)(not returned)(not set)

Replacing the old value is the default for every key. A key can be given a different rule, for example to append to a list instead of overwriting it, but the default is enough for a graph like this one.

One habit matters here: a node should return its changes, not modify the dictionary it was given. Writing state["topic"] = topic inside a node goes around the merge, so the library never sees it as an update. Returning {"topic": topic} keeps every change visible and in one place.

Because a node is still an ordinary function, you can call it directly: classify({"question": "Where is my invoice?"}) returns {"topic": "billing"} without any graph around it.

True or false?

A node has to return every key of the state, or the keys it leaves out are lost.

False. A node returns only the keys it changes. Keys missing from the update keep their previous values.

When a node returns a key that already has a value, the new value replaces the old one by default.

True. With no special rule attached to the key, the last value written wins.

Setting state["topic"] inside a node is a fine way to update the state.

False. Nodes should return their updates. Changing the dictionary they receive goes around the merge LangGraph performs.

Edges: which node runs after which

Nodes alone are a set of functions with no order. Edges supply the order. A normal edge is a fixed connection: after node A finishes, node B runs, every time. Two special markers complete the picture. START stands for the point where the input enters the graph, so an edge from START says which node runs first. END stands for the point where a path stops, so an edge to END says that nothing runs after that node.

  • START input enters

    A marker, not a function you write. The input you invoke the graph with becomes the first state here.

  • classify sets topic
  • answer sets answer
  • END path stops

    A marker for where a path stops. When no node is left to run, the run is over and the final state is returned.

  • START to classify
  • classify to answer
  • answer to END

In code, you create a builder with StateGraph, passing it the state schema, then add the nodes and the edges. add_node registers a function under a name, and add_edge connects two names. START and END are imported from langgraph.graph.

Nodes and edges on a builder
from langgraph.graph import END, START, StateGraph

builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("answer", answer)

builder.add_edge(START, "classify")
builder.add_edge("classify", "answer")
builder.add_edge("answer", END)

The edges name nodes by the names given to add_node. If you pass only the function, as in builder.add_node(classify), the function's name becomes the node's name. START and END are reserved: they are markers the library handles itself, not nodes you write, and using either as a node name is an error. An edge cannot leave END or point at START.

True or false?

START and END are nodes you have to define as functions.

False. They are markers built into the library. You connect your nodes to them with edges, and you cannot add nodes with those names.

A normal edge from classify to answer means answer runs after classify on every run.

True. A normal edge is a fixed connection. Choosing the next node at run time needs a different kind of edge.

Compile, then invoke

A builder with nodes and edges is still only a description. Before it can run, you compile it. Compiling checks the structure of the graph (how its nodes and edges fit together) and raises an error when that structure is broken. It returns a compiled graph, the object that can actually run. Compiling is also where options for the run are attached, such as saving state between runs.

Then you invoke the compiled graph with an initial state. The input does not need every key: here only the question is known at the start. The run follows the edges from START, each node's update is merged into the state, and when the path reaches END, invoke returns the final state.

Compile and invoke
graph = builder.compile()

result = graph.invoke({"question": "Where is my invoice?"})
print(result)
{'question': 'Where is my invoice?', 'topic': 'billing', 'answer': 'Invoices are under Account, then Billing.'}

Following the state through the run shows what each step contributed. The input fills one key, each node adds the key it returns, and nothing a node did not mention changes.

The state after each step of one run
Afterquestiontopicanswer
the input"Where is my invoice?"(not set)(not set)
classify"Where is my invoice?""billing"(not set)
answer"Where is my invoice?""billing""Invoices are under Account, then Billing."

Each call to invoke is one independent run. A second call with another question starts again from its own input and returns its own final state; by default nothing is carried over from the first. The builder methods also return the builder, so the same graph is often written as one chain: StateGraph(State).add_node(...).add_edge(...).compile().

True or false?

You can call invoke on the StateGraph builder as soon as its nodes and edges are added.

False. The builder has to be compiled first. invoke is a method of the compiled graph that compile returns.

The input to invoke may contain only some of the keys in the state schema.

True. The input is the starting state. Keys it leaves out are filled in by the nodes that return them.

invoke returns only the update of the last node that ran.

False. It returns the whole final state, with the values every node wrote along the way.