What You'll Build in This LangGraph Tutorial
This LangGraph tutorial for beginners teaches the framework in three small steps. First you build a study-plan graph from plain Python functions, so you can see how state flows between nodes without paying for a model. Then you add memory with a checkpointer and a thread ID. Finally you turn the same pattern into a tool-using AI agent that looks up your notes and does the maths. The code follows the official LangGraph quickstart and was run against LangGraph 1.2.24.
If you have not built an agent before, read our AI agent tutorial in Python first. It writes the same decide β act β observe loop by hand. LangGraph gives that loop a clear structure, saved state and easy branching.
Prerequisites
- Basic Python: functions, dictionaries, type hints and virtual environments.
- Python 3.10 or newer and a terminal.
- For step 5 only: an Anthropic API key. API calls are billed per token; this project sends a few short requests.
- Helpful: the AI Agents & Automation track and AI agents for beginners.
Learn LangGraph Step by Step
1 Install LangGraph
Create a project folder and a virtual environment, then install the packages the official quickstart uses. langgraph provides the graph, langchain provides messages and tools, and langchain-anthropic connects to Claude.
mkdir study-graph && cd study-graph
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -U langgraph langchain langchain-anthropic
2 Understand state, nodes and edges
A LangGraph app has three parts:
- State is a typed dictionary that every step can read. Each node returns only the keys it wants to change.
- Nodes are ordinary Python functions. They take the state and return an update.
- Edges decide which node runs next. A normal edge always goes to the same node. A conditional edge calls a function that picks the next node.
One more idea matters a lot: a reducer. By default, a node's update replaces the old value. If you annotate a list with operator.add, LangGraph appends new items instead. This is how agents keep a growing list of messages.
3 Build your first graph (no API key needed)
Save this as graph_basics.py. It builds a study plan. Every plan gets an outline and practice, and only sessions of 45 minutes or more get a revision step. That choice is made by a conditional edge.
# graph_basics.py - your first LangGraph graph (no API key needed)
import operator
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
class StudyState(TypedDict):
topic: str
minutes: int
plan: Annotated[list[str], operator.add] # reducer: new items are appended
def make_outline(state: StudyState) -> dict:
return {"plan": [f"Read the basics of {state['topic']}"]}
def add_practice(state: StudyState) -> dict:
return {"plan": ["Solve 5 practice questions"]}
def add_revision(state: StudyState) -> dict:
return {"plan": ["Revise with flashcards for 10 minutes"]}
def route_by_time(state: StudyState) -> str:
# Conditional edge: return the name of the next node
return "add_revision" if state["minutes"] >= 45 else END
builder = StateGraph(StudyState)
builder.add_node("make_outline", make_outline)
builder.add_node("add_practice", add_practice)
builder.add_node("add_revision", add_revision)
builder.add_edge(START, "make_outline")
builder.add_edge("make_outline", "add_practice")
builder.add_conditional_edges("add_practice", route_by_time, ["add_revision", END])
builder.add_edge("add_revision", END)
graph = builder.compile()
if __name__ == "__main__":
short = graph.invoke({"topic": "Ohm's law", "minutes": 30, "plan": []})
long = graph.invoke({"topic": "Ohm's law", "minutes": 60, "plan": []})
print(short["plan"])
print(long["plan"])
Run python graph_basics.py. You should see:
["Read the basics of Ohm's law", 'Solve 5 practice questions']
["Read the basics of Ohm's law", 'Solve 5 practice questions', 'Revise with flashcards for 10 minutes']
Notice that no node rebuilt the whole list. Each one returned a single item, and the operator.add reducer joined them. The third argument to add_conditional_edges lists the nodes the router may choose, which helps LangGraph draw and check the graph.
4 Add memory with a checkpointer
Agents need to remember earlier turns. In LangGraph you get this by compiling the graph with a checkpointer and passing a thread_id. Every run with the same thread ID continues from the saved state. Save this as memory_demo.py next to the first file:
# memory_demo.py - the same graph, now with memory
from langgraph.checkpoint.memory import InMemorySaver
from graph_basics import builder
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "student-1"}}
graph.invoke({"topic": "Ohm's law", "minutes": 30, "plan": []}, config)
graph.invoke({"topic": "Kirchhoff's laws", "minutes": 30}, config)
print(graph.get_state(config).values["plan"])
The second call adds to the first plan instead of starting again:
["Read the basics of Ohm's law", 'Solve 5 practice questions', "Read the basics of Kirchhoff's laws", 'Solve 5 practice questions']
Change the thread ID to "student-2" and the plan starts empty. InMemorySaver loses everything when the program stops, so it is only for learning and tests. Real apps use a database-backed checkpointer.
5 Turn it into a tool-using AI agent
Now replace the hand-written nodes with a model and tools. The structure matches the official LangGraph quickstart: one node calls the model, one node runs the tools it asked for, and a conditional edge loops between them until the model stops asking. Set your key first (export ANTHROPIC_API_KEY="your-key"), then save this as agent.py:
# agent.py - a tool-using study agent built with LangGraph
import operator
from typing import Annotated, Literal
from typing_extensions import TypedDict
from langchain.chat_models import init_chat_model
from langchain.messages import AnyMessage, HumanMessage, SystemMessage, ToolMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
NOTES = {
"ohms law": "V = I x R. Voltage equals current times resistance.",
"power": "P = V x I. Power equals voltage times current.",
}
@tool
def lookup_note(topic: str) -> str:
"""Look up the student's saved note on a physics topic.
Args:
topic: Topic name, for example "ohms law" or "power"
"""
key = topic.lower().replace("'", "").strip()
return NOTES.get(key, f"No note saved for '{topic}'.")
@tool
def multiply(a: float, b: float) -> float:
"""Multiply a and b.
Args:
a: First number
b: Second number
"""
return a * b
tools = [lookup_note, multiply]
tools_by_name = {t.name: t for t in tools}
model = init_chat_model("claude-haiku-5-5", temperature=0) # check the models page for current IDs
model_with_tools = model.bind_tools(tools)
class AgentState(TypedDict):
messages: Annotated[list[AnyMessage], operator.add]
llm_calls: int
SYSTEM = SystemMessage(content="You are a study helper. Use the notes tool before "
"answering physics questions and show the formula you used.")
def call_model(state: AgentState) -> dict:
reply = model_with_tools.invoke([SYSTEM] + state["messages"])
return {"messages": [reply], "llm_calls": state.get("llm_calls", 0) + 1}
def run_tools(state: AgentState) -> dict:
results = []
for call in state["messages"][-1].tool_calls:
tool_fn = tools_by_name.get(call["name"])
output = tool_fn.invoke(call["args"]) if tool_fn else f"Unknown tool {call['name']}"
results.append(ToolMessage(content=str(output), tool_call_id=call["id"]))
return {"messages": results}
MAX_LLM_CALLS = 6
def should_continue(state: AgentState) -> Literal["run_tools", END]:
last = state["messages"][-1]
if last.tool_calls and state["llm_calls"] < MAX_LLM_CALLS:
return "run_tools"
return END
builder = StateGraph(AgentState)
builder.add_node("call_model", call_model)
builder.add_node("run_tools", run_tools)
builder.add_edge(START, "call_model")
builder.add_conditional_edges("call_model", should_continue, ["run_tools", END])
builder.add_edge("run_tools", "call_model")
agent = builder.compile(checkpointer=InMemorySaver())
if __name__ == "__main__":
config = {"configurable": {"thread_id": "demo"}}
question = "Using my notes on Ohm's law, what is the voltage at 0.5 A and 220 ohms?"
result = agent.invoke({"messages": [HumanMessage(content=question)], "llm_calls": 0}, config)
for message in result["messages"]:
message.pretty_print()
Run python agent.py. The wording changes between runs, but the printed messages follow this order: your question, an AI message asking for lookup_note, the tool result, an AI message asking for multiply with 0.5 and 220, the result 110.0, and a final answer of 110 volts. We tested the graph wiring with a stand-in model that returns those tool calls, and the loop ran exactly three model calls before stopping.
6 Understand the safety limits
- A hard stop.
MAX_LLM_CALLSends the loop even if the model keeps asking for tools, which caps both runaway loops and cost. LangGraph also has its own recursion limit, which you can set per run withconfig["recursion_limit"]. - An allowlist. Only functions in
tools_by_namecan run. An invented tool name gets a message, not a crash. - Narrow, read-only tools. Neither tool can write files or reach the network. Add a human approval step before any tool that changes data.
- Secrets in the environment. The API key never appears in the code.
These limits matter more every month. Security agencies are now reporting real AI agent cyberattacks built on open-source agent frameworks, and agents that read web pages or files can be steered by prompt injection.
Practice Task
Extend the project on your own, then check yourself with the quiz below.
- In
graph_basics.py, add alevelkey to the state and a second conditional edge that adds "Try 2 JEE-level problems" only whenlevel == "advanced". - Remove the
operator.addannotation fromplanand run the graph again. What happens to the plan, and why? - In
agent.py, add adivide(a, b)tool that returns a clear message instead of crashing whenbis zero. - Ask the agent a follow-up question on the same
thread_id, such as "And what is the power?". Check that it uses the earlier answer from memory.
LangGraph Tutorial Quiz
Five quick questions on this tutorial.
Frequently Asked Questions
What is LangGraph used for?
LangGraph is a Python and JavaScript framework for building agents and workflows as graphs. It handles state, branching, loops, memory and human-in-the-loop steps, so you can control exactly how an agent moves from one step to the next.
Is LangGraph the same as LangChain?
No. They come from the same company and work together. LangChain provides model, message and tool interfaces, and LangGraph provides the graph runtime that orchestrates them. You can use LangGraph nodes that never call LangChain at all, as in step 3.
Can I learn LangGraph for free?
Yes. LangGraph is open source, and steps 1 to 4 of this tutorial run without any API key. Only the model calls in step 5 cost money, and a few short requests cost very little.
Should I learn LangGraph before building agents by hand?
It is easier the other way round. Write a small agent loop by hand first, then use LangGraph when you need saved state, branching or several agents working together.
Sources
- LangChain Docs: LangGraph overview
- LangChain Docs: LangGraph quickstart (the model node, tool node and conditional edge pattern)
- LangChain Docs: Use the Graph API (state, reducers and edges)
- LangGraph on PyPI
- Claude Docs: Models overview (current model IDs)
Code checked with LangGraph 1.2.24 and LangChain 1.5.2 on November 28, 2026. Model IDs change over time, so check the models page if the one in init_chat_model is retired.