Single-agent systems excel at focused tasks: research, writing, analysis. Multi-agent systems add a different dimension: coordination. When you need specialized agents working together, handling failures gracefully, and routing decisions based on context, that’s where LangGraph’s state graph architecture becomes essential. I’ve built several multi-agent systems in production, and the difference between a fragile script and a reliable system comes down to how you structure state, routing, and orchestration.
Why Multi-Agent Systems Matter
A single LLM agent can reason, plan, and use tools. As complexity grows, so does token usage, latency, and error surface area. Multi-agent systems let you decompose problems: one agent focuses on data gathering, another on validation, another on synthesis. Each agent is simpler, more focused, and easier to test and monitor.
The real value isn’t in building agents individually. It’s in orchestrating them: deciding which agent runs next, passing state between them cleanly, handling failures, and ensuring the system converges on a solution. This is where LangGraph shines.
Understanding State Graphs
At its core, LangGraph models your system as a directed graph where nodes are computational steps (agent runs, tool calls, decisions) and edges define transitions. State flows through the graph, updated at each node. This is fundamentally different from chaining individual LLM calls.
A state graph gives you:
- Explicit control flow that you can visualize and debug
- Persistent state that each node can read and modify
- Conditional routing based on state, not just sequential execution
- Built-in checkpointing for fault tolerance and resumption
Let’s build a simple example: a research agent team that gathers information, fact-checks it, and produces a report.
Defining Your State Schema
Start by defining what state your system needs. This is your contract between nodes.
from typing import Annotated, TypedDict, Sequence
from langchain_core.messages import BaseMessage
class ResearchState(TypedDict):
task: str
gathered_info: list[str]
fact_checks: list[dict]
errors: list[str]
report: str
messages: Annotated[Sequence[BaseMessage], lambda x, y: x + y]
The Annotated type for messages is important: it tells LangGraph how to merge messages from different nodes. Here, we’re appending them. Each field represents something your agents will contribute to. The messages field is a common pattern for tracking conversation history and reasoning steps.
Building a Supervisor Agent
In a multi-agent system, a supervisor (or orchestrator) decides which worker agent should act next. It reads the current state and routes conditionally.
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.graph import StateGraph, END
llm = ChatOpenAI(model="gpt-4", temperature=0)
@tool
def search_web(query: str) -> str:
"""Search for information about the query."""
return f"Information about {query}..."
@tool
def fact_check(claim: str) -> str:
"""Verify if a claim is accurate."""
return f"Fact check result for: {claim}"
supervisor_prompt = """You are a research supervisor. Based on the current task and gathered information, decide what to do next.
Options:
- gather_info: Call this if you need to search for more information
- verify: Call this if you have gathered enough info and need to verify facts
- report: Call this if verification is complete and you're ready to write the report
- end: Call this if the task is complete
Respond with only the action name."""
def supervisor_node(state: ResearchState):
messages = state["messages"]
messages.append(("system", supervisor_prompt))
messages.append(("user", f"Task: {state['task']}
Gathered info: {state['gathered_info']}"))
response = llm.invoke(messages)
decision = response.content.strip().lower()
return {
"messages": [response]
}
The supervisor is itself an LLM node. It reads state and produces a decision that routes the graph. Notice how it returns state updates (the messages), not the decision directly. We handle routing separately.
Worker Agents and Tool Orchestration
Worker agents are specialized nodes that perform specific tasks. They have access to relevant tools and report results back into state.
from langgraph.prebuilt import create_react_agent
def gather_info_node(state: ResearchState):
"""Worker agent that gathers information."""
task = state["task"]
tools = [search_web]
agent = create_react_agent(llm, tools)
result = agent.invoke({"input": f"Find information about: {task}"})
new_info = result.get("output", "")
return {
"gathered_info": state["gathered_info"] + [new_info],
"messages": state["messages"] + [result]
}
def verify_node(state: ResearchState):
"""Worker agent that fact-checks gathered information."""
info = state["gathered_info"]
tools = [fact_check]
agent = create_react_agent(llm, tools)
checks = []
for item in info:
result = agent.invoke({"input": f"Verify: {item}"})
checks.append({
"claim": item,
"result": result.get("output", "")
})
return {
"fact_checks": checks,
"messages": state["messages"] + [result]
}
def report_node(state: ResearchState):
"""Generate final report from verified information."""
checks = state["fact_checks"]
prompt = f"""Based on these fact-checked findings, write a concise research report:
{checks}
Report:"""
response = llm.invoke(prompt)
return {
"report": response.content,
"messages": state["messages"] + [response]
}
Each worker node is focused: it takes state, processes it with its own agent or logic, and returns updated state. This separation of concerns makes the system easier to test and modify.
Conditional Routing
The supervisor’s decision needs to actually route the graph. LangGraph provides conditional edge routing for this.
from langgraph.graph import StateGraph, END
def route_decision(state: ResearchState):
"""Parse supervisor's decision and route accordingly."""
last_message = state["messages"][-1]
decision = last_message.content.strip().lower()
if "gather" in decision:
return "gather_info"
elif "verify" in decision:
return "verify"
elif "report" in decision:
return "report"
elif "end" in decision:
return END
else:
return "gather_info"
graph = StateGraph(ResearchState)
graph.add_node("supervisor", supervisor_node)
graph.add_node("gather_info", gather_info_node)
graph.add_node("verify", verify_node)
graph.add_node("report", report_node)
graph.add_edge("gather_info", "supervisor")
graph.add_edge("verify", "supervisor")
graph.add_edge("report", "supervisor")
graph.add_conditional_edges(
"supervisor",
route_decision,
{
"gather_info": "gather_info",
"verify": "verify",
"report": "report",
END: END
}
)
graph.set_entry_point("supervisor")
app = graph.compile()
The conditional edge function reads state and returns the next node name. This is where your routing logic lives. You can make decisions based on state content, message count, error flags, or any other criteria.
Running and Monitoring
Once compiled, the graph runs like any LangChain runnable.
initial_state = {
"task": "Research the history of LLMs",
"gathered_info": [],
"fact_checks": [],
"errors": [],
"report": "",
"messages": []
}
final_state = app.invoke(initial_state)
print(final_state["report"])
For production systems, use streaming and checkpointing:
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()
app = graph.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "research-123"}}
for event in app.stream(initial_state, config):
print(event)
if interrupted:
final_state = app.invoke(None, config)
Checkpointing saves state at each step, letting you resume if something fails. The thread_id groups related executions together, useful for multi-turn conversations or long-running tasks.
Error Handling and Fallback Patterns
Production systems need graceful degradation. Add error tracking to state and fallback nodes.
def gather_info_node_with_fallback(state: ResearchState):
try:
task = state["task"]
result = search_web(task)
return {
"gathered_info": state["gathered_info"] + [result],
"messages": state["messages"]
}
except Exception as e:
return {
"errors": state["errors"] + [str(e)],
"messages": state["messages"]
}
def handle_errors_node(state: ResearchState):
"""Decide what to do if errors occurred."""
if len(state["errors"]) > 2:
return {"report": "Task completed with limitations due to errors."}
else:
return {"messages": state["messages"]}
Add error handling nodes to your graph and route to them conditionally. This prevents cascading failures and gives you visibility into what went wrong.
State Persistence in Production
For long-running workflows or recovery scenarios, persist state to a database.
from langgraph.checkpoint.postgres import PostgresSaver
db_checkpointer = PostgresSaver(
connection_string="postgresql://user:password@localhost/langgraph"
)
app = graph.compile(checkpointer=db_checkpointer)
config = {"configurable": {"thread_id": "workflow-456"}}
final_state = app.invoke(initial_state, config)
state_snapshot = app.get_state(config)
if state_snapshot:
result = app.invoke(None, config)
PostgreSQL checkpointing is built in. For other backends, implement the BaseCheckpointSaver interface. This is critical for workflows that span hours or days.
Scaling Patterns
As your multi-agent system grows, consider these patterns:
- Hierarchical supervision: Supervisors managing other supervisors for deeply nested workflows
- Parallel agents: Use map/reduce patterns to run multiple agents on different data slices concurrently
- Tool caching: Cache tool results to avoid redundant API calls across agents
- Agent specialization: Tune agents for specific domains to reduce hallucination
- Observability: Log state transitions and decisions for debugging and auditing
Common Pitfalls
After building several systems, I’ve noticed patterns that cause problems:
- Oversized state: Storing too much data in state slows down serialization and increases token usage. Keep it lean.
- Ambiguous routing decisions: If your supervisor’s output is unclear, the router will make wrong choices. Be explicit in prompts.
- Missing error boundaries: One agent’s failure cascades to the whole system. Always wrap nodes in try/catch and plan fallbacks.
- Infinite loops: If your routing logic can send the graph back to itself, add a step counter and exit condition.
- Unclear tool definitions: Agents misuse tools if tool descriptions are vague. Write detailed docstrings and examples.
Putting It Together
A complete multi-agent system combines these pieces: a clear state schema, specialized worker agents, a supervisor making intelligent routing decisions, conditional edges, error handling, and persistence. Start small with two or three agents, get the routing and state updates working cleanly, then expand.
The shift from single agents to agent teams opens new possibilities. Each node is simpler, the system is more transparent, and failures are easier to handle. Build one multi-agent system and you’ll find yourself reaching for this pattern repeatedly.
What’s the difference between LangGraph and other multi-agent frameworks?
LangGraph gives you explicit control over state and routing through a graph structure. You define exactly how agents interact and what state flows between them. Other frameworks may abstract these details or use implicit chaining, which works for simple cases but becomes limiting when you need fine-grained control or debugging in production.
Can I use LangGraph with non-OpenAI models?
Yes. LangGraph works with any LangChain-compatible model: Anthropic Claude, Mistral, open-source models via Ollama or HuggingFace, and others. The orchestration logic is model-agnostic. Your agents can even use different models if needed.
How do I handle agent disagreement or conflicting decisions?
Build it into your state and routing. Add a validation node that checks if agents’ outputs conflict, then route to a resolution node (e.g., another agent that synthesizes viewpoints, or a human review step). State tracks what happened, so you can log and analyze conflicts.
Is LangGraph suitable for real-time applications?
Yes, with considerations. Streaming execution is supported, and you can get intermediate results as nodes complete. If your application needs sub-second latency, be mindful of LLM call times and network overhead. For very latency-sensitive work, consider caching supervisor decisions or using smaller, faster models.
What’s the best way to debug a multi-agent system?
Use LangGraph’s built-in visualization to see your graph structure. Enable debug logging on nodes to see what state looks like at each step. Stream execution instead of blocking, so you can inspect intermediate outputs. Store all state snapshots to a database, then replay them locally if something goes wrong.