What is LangGraph?
LangGraph is a library built on top of LangChain for building stateful, multi-actor applications with Large Language Models (LLMs). While LangChain excels at creating linear chains and simple agents, LangGraph enables you to build complex workflows where multiple AI agents can collaborate, branch, loop, and maintain state across interactions.
Think of LangGraph as a way to define your AI application as a graph, where nodes represent actions (like calling an LLM or a tool), and edges define the flow between them.
Why LangGraph?
Traditional LLM applications face limitations when building complex systems:
- Linear chains are limiting: Real workflows often need branching, loops, and conditional logic
- State management is hard: Tracking information across multiple steps and actors is complex
- Multi-agent coordination: Multiple AI agents need to collaborate and share context
- Human-in-the-loop: Many applications need checkpoints for human approval
- Error recovery: Complex systems need ways to retry or take alternative paths
LangGraph addresses all of these with a graph-based approach to application design.
Core Concepts
1. State
Every LangGraph application has a state that persists across the entire workflow:
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph
class AgentState(TypedDict):
messages: list[str]
current_step: str
research_data: dict
final_answer: str
# State is automatically passed between nodes
# and can be updated by any node
2. Nodes
Nodes are the building blocks - functions that perform actions and update state:
def researcher_node(state: AgentState) -> AgentState:
"""Research node that gathers information"""
# Access current state
query = state["messages"][-1]
# Perform research (call LLM, APIs, etc.)
research_results = perform_research(query)
# Return updated state
return {
"research_data": research_results,
"current_step": "research_complete"
}
def writer_node(state: AgentState) -> AgentState:
"""Writer node that creates content"""
research = state["research_data"]
# Generate content based on research
content = generate_content(research)
return {"final_answer": content}
3. Edges
Edges define how nodes connect - they can be direct or conditional:
from langgraph.graph import StateGraph, END
# Create the graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("researcher", researcher_node)
workflow.add_node("writer", writer_node)
workflow.add_node("reviewer", reviewer_node)
# Add edges
workflow.add_edge("researcher", "writer") # Direct edge
# Conditional edge based on state
def should_revise(state):
if state.get("needs_revision"):
return "writer" # Go back to writer
return END # Finish
workflow.add_conditional_edges("reviewer", should_revise)
# Set entry point
workflow.set_entry_point("researcher")
4. Checkpoints
Persist state for human-in-the-loop or recovery:
from langgraph.checkpoint.sqlite import SqliteSaver
# Create checkpointer
checkpointer = SqliteSaver.from_conn_string(":memory:")
# Compile with checkpointing
app = workflow.compile(checkpointer=checkpointer)
# Run with thread ID for persistence
config = {"configurable": {"thread_id": "user-123"}}
result = app.invoke(initial_state, config)
# Later, resume from checkpoint
resumed = app.invoke(None, config) # Continues from last state
Building a Multi-Agent System
Here's a complete example of a research assistant with multiple specialized agents:
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
class ResearchState(TypedDict):
query: str
search_results: list
analysis: str
report: str
approved: bool
def search_agent(state):
"""Searches for relevant information"""
results = web_search(state["query"])
return {"search_results": results}
def analyst_agent(state):
"""Analyzes search results"""
llm = ChatOpenAI(model="gpt-4")
analysis = llm.invoke(f"Analyze: {state['search_results']}")
return {"analysis": analysis.content}
def writer_agent(state):
"""Writes the final report"""
llm = ChatOpenAI(model="gpt-4")
report = llm.invoke(f"Write report based on: {state['analysis']}")
return {"report": report.content}
def human_review(state):
"""Checkpoint for human approval"""
# In production, this would wait for human input
return {"approved": True}
def route_after_review(state):
if state["approved"]:
return END
return "analyst" # Revise if not approved
# Build the graph
workflow = StateGraph(ResearchState)
workflow.add_node("search", search_agent)
workflow.add_node("analyst", analyst_agent)
workflow.add_node("writer", writer_agent)
workflow.add_node("review", human_review)
workflow.set_entry_point("search")
workflow.add_edge("search", "analyst")
workflow.add_edge("analyst", "writer")
workflow.add_edge("writer", "review")
workflow.add_conditional_edges("review", route_after_review)
app = workflow.compile()
Common Patterns
Supervisor Pattern
A supervisor agent delegates tasks to specialized worker agents and coordinates their outputs.
Hierarchical Teams
Multiple teams of agents, each with their own supervisor, working on complex projects.
Plan-and-Execute
A planner creates a task list, and an executor works through each task sequentially.
Reflection
An agent generates output, then critiques and improves it in a loop until satisfied.
Human-in-the-Loop
Checkpoints allow humans to review, approve, or modify agent decisions.
Tool-Using Agents
Agents that can dynamically select and use tools based on the task at hand.
LangGraph vs. Other Frameworks
| Feature | LangGraph | LangChain Agents | AutoGen |
|---|---|---|---|
| State Management | Built-in, typed | Limited | Message-based |
| Workflow Control | Full graph control | Linear/ReAct | Conversation-based |
| Checkpointing | Native support | Manual | Limited |
| Human-in-the-Loop | First-class | Possible | Conversation-based |
| Debugging | Excellent (LangSmith) | Good | Limited |
Getting Started
# Install LangGraph
pip install langgraph langchain-openai
# Basic usage
from langgraph.graph import StateGraph, END
class State(TypedDict):
messages: list[str]
def chatbot(state):
return {"messages": state["messages"] + ["Hello!"]}
workflow = StateGraph(State)
workflow.add_node("chat", chatbot)
workflow.set_entry_point("chat")
workflow.add_edge("chat", END)
app = workflow.compile()
result = app.invoke({"messages": ["Hi"]})
Master LangGraph with Expert Guidance
Our Agentic AI program includes hands-on projects building multi-agent systems with LangGraph. Learn to design, implement, and deploy complex AI workflows with personalized mentorship.
Explore Agentic AI Program