Building Multi-Agent Systems with LangGraph: Architecture and Patterns
LangGraph is the framework Anthropic, OpenAI, and most serious AI engineering teams have converged on for building stateful, multi-step agent systems. It models agentic workflows as directed graphs — nodes are processing steps, edges are transitions, and state is explicitly defined and persisted across the full run.
This article goes past the documentation and covers the architectural patterns, failure modes, and production considerations you need for systems that work at scale.
Why Graph-Based Architecture?
Before LangGraph, most agent frameworks used either a simple ReAct loop (reason → act → observe, repeat) or linear chains. Both have fundamental limitations:
ReAct loops have no explicit control over termination or branching. The LLM decides when to stop and what to do next, which creates unpredictable behavior and makes it hard to reason about correctness.
Linear chains are predictable but inflexible. They cannot branch, retry, or loop based on intermediate results.
LangGraph gives you the control flow of a regular program (conditions, loops, parallelism) combined with the reasoning capability of a language model. You define the graph; the LLM handles the reasoning within each node.
Core Concepts
State
State is the shared data structure passed between every node in the graph. Define it as a TypedDict with explicit types:
from typing import TypedDict, Annotated
from langgraph.graph.message import add_messages
class AgentState(TypedDict):
messages: Annotated[list, add_messages]
contact_id: str | None
lead_score: float | None
current_step: str
errors: list[str]
The Annotated type with add_messages is a reducer — it tells LangGraph how to merge updates to that field (append new messages rather than replace).
Nodes
Nodes are Python functions that receive the current state and return a partial state update:
def enrich_lead(state: AgentState) -> AgentState:
contact = crm.get_contact(state["contact_id"])
score = scoring_model.score(contact)
return {
"lead_score": score,
"current_step": "enriched",
}
Nodes can call tools, invoke LLMs, query databases, or run any arbitrary logic. They do not need to know about other nodes — they just read from state and write back to state.
Edges
Edges define how the graph transitions between nodes. There are two types:
Fixed edges always go to the same next node:
graph.add_edge("enrich_lead", "update_crm")
Conditional edges route based on state:
def route_by_score(state: AgentState) -> str:
if state["lead_score"] >= 0.8:
return "assign_senior_rep"
elif state["lead_score"] >= 0.4:
return "add_to_nurture"
else:
return "archive"
graph.add_conditional_edges("score_lead", route_by_score)
The routing function receives the full state and returns the name of the next node as a string. This is pure Python — no LLM involved in routing unless you want it to be.
Multi-Agent Patterns
Supervisor + Specialists
The most common production pattern: one supervisor agent receives the task, breaks it down, and delegates to specialist agents.
# Supervisor decides which specialist to call
def supervisor(state: AgentState) -> AgentState:
decision = llm.invoke([
SystemMessage("You are a sales workflow supervisor. Decide which specialist to call."),
HumanMessage(f"Task: {state['task']}. Available: [enrichment, outreach, scheduling]")
])
return {"next_agent": decision.content}
# Conditional edge routes to the right specialist
graph.add_conditional_edges(
"supervisor",
lambda s: s["next_agent"],
{
"enrichment": "enrichment_agent",
"outreach": "outreach_agent",
"scheduling": "scheduling_agent",
}
)
This pattern works well when tasks are heterogeneous and the supervisor can reliably classify them. It breaks down when classification accuracy is below ~85% — add a confidence threshold and route uncertain cases to a human queue.
Parallel Execution
LangGraph supports fan-out to parallel nodes natively:
# Both nodes run concurrently
graph.add_edge("orchestrator", "entra_provisioning")
graph.add_edge("orchestrator", "jira_task_creation")
# Fan-in: both must complete before proceeding
graph.add_edge(["entra_provisioning", "jira_task_creation"], "send_confirmation")
Use parallelism for independent operations that can run concurrently — provisioning an account while creating a support ticket, for example. Do not use it for operations with data dependencies.
Reflection and Self-Correction
One of the most powerful patterns: an agent generates output, a critic evaluates it, and the agent revises if the quality is insufficient.
def draft_email(state: AgentState) -> AgentState:
draft = llm.invoke(...)
return {"email_draft": draft, "revision_count": 0}
def critique_email(state: AgentState) -> AgentState:
critique = llm.invoke([
SystemMessage("Evaluate this sales email for clarity, tone, and personalization."),
HumanMessage(state["email_draft"])
])
return {"critique": critique, "needs_revision": "REVISE" in critique.content}
def route_revision(state: AgentState) -> str:
if state["needs_revision"] and state["revision_count"] < 3:
return "draft_email" # loop back
return "send_email"
Add a maximum revision count to prevent infinite loops. In practice, one revision pass improves quality significantly; three passes rarely improves over two.
Checkpointing and Persistence
LangGraph supports checkpointing — saving the full state at each node so the workflow can be resumed after failures or interruptions.
from langgraph.checkpoint.postgres import PostgresSaver
checkpointer = PostgresSaver.from_conn_string(DATABASE_URL)
graph = graph.compile(checkpointer=checkpointer)
# Start a new run
config = {"configurable": {"thread_id": "run-abc123"}}
result = graph.invoke(initial_state, config=config)
# Resume after failure
result = graph.invoke(None, config=config) # picks up from last checkpoint
Checkpointing is essential for long-running workflows and for human-in-the-loop patterns where the graph pauses waiting for approval.
Human-in-the-Loop
LangGraph has built-in support for interrupting execution and waiting for human input:
graph.add_node("human_approval", lambda s: s) # passthrough node
graph.compile(interrupt_before=["send_contract"]) # pause before this node
When the graph reaches the interrupt point, execution stops and the current state is returned. After the human reviews and approves, you resume:
# Resume with human feedback injected into state
graph.invoke(
{"approved": True, "approver": "jane@company.com"},
config={"configurable": {"thread_id": "run-abc123"}}
)
Use human-in-the-loop for any irreversible action with meaningful business impact: sending contracts, issuing refunds, deleting data, making external commitments.
Production Hardening
Token Budget Management
Long-running agents accumulate messages that bloat the context window. Implement a summarization step that fires when message count exceeds a threshold:
def summarize_if_needed(state: AgentState) -> AgentState:
if len(state["messages"]) > 20:
summary = llm.invoke(
[SystemMessage("Summarize the conversation so far in 3 bullet points.")] +
state["messages"]
)
return {"messages": [SystemMessage(f"Summary: {summary.content}")]}
return {}
Structured Tool Output
Always validate tool call outputs against a schema before injecting them into state:
from pydantic import BaseModel
class ContactRecord(BaseModel):
id: str
email: str
company: str
score: float = 0.0
def safe_get_contact(contact_id: str) -> ContactRecord:
raw = crm.get(contact_id)
return ContactRecord.model_validate(raw) # raises on invalid data
Unvalidated tool output is one of the most common sources of downstream failures in production agents.
Observability
Instrument every node with tracing:
from langsmith import traceable
@traceable(name="enrich_lead")
def enrich_lead(state: AgentState) -> AgentState:
...
LangSmith (LangChain's observability product) captures the full trace, including every LLM call, tool invocation, and state transition. Alternatives: Langfuse, Arize, or custom OpenTelemetry instrumentation.
When Not to Use LangGraph
LangGraph adds complexity. For simple linear workflows with no branching or state persistence requirements, a plain Python script with sequential function calls is better. Use LangGraph when you need:
- Conditional routing between multiple paths
- State that persists across steps and across sessions
- Human-in-the-loop interrupts
- Parallel execution of independent branches
- Reflection loops with self-correction
For everything else, the overhead is not worth it.
LangGraph is the right foundation for production multi-agent systems. The graph model maps naturally to how complex workflows actually behave — branching, retrying, waiting, persisting — and the explicit state definition catches a whole class of bugs at design time rather than runtime.