FromZero2AI
CoursesPlaygroundBlog
Support on Ko-fi
AI Agent Frameworks • Module A: LangChain & LangGraphLesson 2: Stateful Agents with LangGraph
PreviousNext

Lesson 2: Stateful Agents with LangGraph

Model agent behavior as a state graph: define nodes, edges, and conditional routing. Build a ReAct agent that loops until done — with full control over state at each step.

Built with AI for beginners. Free forever.

Support on Ko-fi•About•Blog•Privacy Policy•Terms of Service

LangGraph solves the problem that LangChain chains cannot: agents that loop, branch, and maintain state across multiple model calls. It models your agent as a directed graph where nodes are functions and edges control the flow.

The ReAct Loop as a Graph

The ReAct pattern (Reason + Act) is the most common agent architecture:

START→agent→ tool call?YES →tools→agent... (loop)
START→agent→ no tool call?→END

Building the Graph: Step by Step

State is a TypedDict that flows through the graph. Every node reads from and writes to state. Define all fields upfront.

from typing import TypedDict, Annotated
from langgraph.graph.message import add_messages

class AgentState(TypedDict):
    # Messages accumulate — add_messages merges rather than replaces
    messages: Annotated[list, add_messages]
    # Custom state fields
    research_results: list[str]
    final_answer: str
    iterations: int

LangGraph vs. AgentExecutor

FeatureAgentExecutor (legacy)LangGraph
Control flowBlack box loopExplicit graph — full control
Custom routingLimitedFull conditional branching
Multi-agentNot supportedFirst-class: sub-graphs, handoffs
PersistenceNoCheckpointers (memory, Redis, Postgres)
Human-in-the-loopHackyBuilt-in interrupt/resume

In the next lesson, we explore the different memory strategies available to LangGraph agents: short-term (within-thread), long-term (cross-thread), and episodic memory.