LangChain · Lesson 12 of 15
LangGraph Basics
State graphs, cycles, conditional edges and checkpointing a long-running agent.
- Advanced
- 18 min read
- 3 objectives
Before this lessonLesson 11: Structured Output and Tool Calling
What you will learn
- Define state
- Add a cycle
- Checkpoint a thread
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
LangGraph models an agent as a state machine: nodes are functions, edges decide the next node, and a checkpointer stores state per thread so a run can pause.
State and a cycle
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, END
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list, add_messages]
steps: int
def agent(state: State):
reply = model.bind_tools([search]).invoke(state["messages"])
return {"messages": [reply], "steps": state.get("steps", 0) + 1}
def more(state: State):
last = state["messages"][-1]
if state["steps"] >= 4:
return END
return "tools" if getattr(last, "tool_calls", None) else END
g = StateGraph(State)
g.add_node("agent", agent)
g.add_node("tools", tool_node)
g.set_entry_point("agent")
g.add_conditional_edges("agent", more)
g.add_edge("tools", "agent")
app = g.compile()Checkpoints
from langgraph.checkpoint.memory import MemorySaver
app = g.compile(checkpointer=MemorySaver())
app.invoke({"messages": [("user", "Find the refund policy")]}, {"configurable": {"thread_id": "u-1"}})The same thread_id resumes. Swap MemorySaver for a Postgres checkpointer in production.
