
Artificial intelligence applications are becoming more sophisticated. Instead of asking a single AI model to handle every task, developers can build systems in which multiple AI agents collaborate to solve complex problems.
For example, an AI research assistant might need to collect information, analyze it, write a summary, and review the final result. A single LLM can attempt all these steps, but a multi-agent architecture allows each agent to focus on a specific responsibility.
This is where LangGraph becomes useful.
LangGraph is a framework for building stateful, multi-step AI applications. It allows developers to define workflows, manage shared state, control execution paths, and coordinate multiple agents.
In this guide, you'll learn:
What multi-agent AI systems are.
Why LangGraph is useful for agent orchestration.
How nodes, edges, and state work.
How to build a multi-agent AI system using Node.js and TypeScript.
How to coordinate researcher, writer, and reviewer agents.
How to handle errors and improve the system for production.
Let's get started.
1. What Is a Multi-Agent AI System?
A multi-agent AI system consists of multiple AI agents that collaborate to complete a task.
Each agent has a specific role, instructions, and responsibilities. Depending on the architecture, agents can work sequentially, conditionally, or in parallel.
Consider an AI blog-writing assistant.
Instead of using one model to complete everything, you could divide the workflow into three agents:
Researcher Agent
Identifies important topics.
Organizes relevant information.
Produces research notes.
Writer Agent
Uses the research notes to create a draft.
Organizes the content into sections.
Improves readability.
Reviewer Agent
Checks the draft for missing information.
Identifies unsupported claims.
Suggests improvements before the content is finalized.
The agents collaborate through a shared workflow, with each one contributing to the final output.
How a Multi-Agent System Works
A typical workflow looks like this:
User Request → Researcher Agent → Writer Agent → Reviewer Agent → Final Response
More advanced systems can make decisions dynamically. For example, if the reviewer identifies problems, the workflow can send the draft back to the writer instead of returning an incomplete result.
This ability to control execution paths makes multi-agent systems useful for complex AI applications.
2. What Is LangGraph?
LangGraph is a framework from the LangChain ecosystem for building stateful AI workflows and agents.
It represents an application as a graph containing nodes and edges.
Each node performs an operation, such as calling an LLM, executing a tool, or processing data. Edges determine which node executes next.
LangGraph is particularly useful when an AI application requires:
Multiple specialized agents.
Conditional execution.
Shared state between steps.
Iterative refinement.
Human approval before sensitive actions.
Checkpointing and resumable workflows.
Unlike a simple sequence of LLM calls, a LangGraph workflow can make decisions about what should happen next.
For example, a reviewer can send content back for revision, while a supervisor can decide whether additional research is necessary.
You can explore the official documentation at LangGraph Documentation.
3. Understanding the Core Components of LangGraph
Before implementing a multi-agent system, it's important to understand the fundamental building blocks.
3.1. Nodes
Nodes represent individual operations in a graph.
A node might:
Call an LLM.
Execute a specialized agent.
Retrieve documents from a vector database.
Call an external API.
Validate an output.
In our example, the researcher, writer, reviewer, and supervisor will each be represented by nodes.
3.2. Edges
Edges define how control moves between nodes.
For example:
Researcher → Writer → Reviewer
This is a straightforward workflow in which each node runs in a predetermined order.
LangGraph also supports conditional edges, allowing the application to select the next node based on the current state.
For example:
Reviewer → Approved → Finish
Or:
Reviewer → Needs Changes → Writer
3.3. State
State is the shared information available to the graph as it executes.
For our blog-writing application, the state might contain:
The original user request.
Research notes.
The generated draft.
Review feedback.
The current workflow decision.
Each node can read relevant information from the state and return updates.
This makes it possible for agents to collaborate without manually passing every value through a long chain of function calls.
3.4. Conditional Routing
Conditional routing allows the workflow to make decisions dynamically.
For example, a supervisor agent can decide whether the next step should be research, writing, reviewing, or finishing.
This is useful when the correct execution path depends on the user's request or the output of a previous agent.
4. Project Architecture
We'll build a simple multi-agent AI system with four components.
Component | Responsibility |
|---|---|
Supervisor Agent | Decides which specialist should run next |
Researcher Agent | Creates research notes for the requested topic |
Writer Agent | Converts research notes into a structured draft |
Reviewer Agent | Reviews the draft and decides whether it needs revision |
The supervisor coordinates the workflow, while the specialist agents focus on their assigned tasks.
The basic architecture is:
User Request → Supervisor → Researcher → Supervisor → Writer → Supervisor → Reviewer
After reviewing the draft, the reviewer can either approve it or request revisions. The supervisor then decides whether to return to the writer or finish the workflow.
For this tutorial, we'll use a simplified implementation in which each specialist is an LLM-powered node. In a production application, you could extend these nodes with tools, retrieval systems, APIs, and other capabilities.
5. Set Up the Node.js Project
First, create a new Node.js project.
mkdir langgraph-multi-agent
cd langgraph-multi-agent
npm init -yInstall the required dependencies:
npm install @langchain/langgraph @langchain/openai @langchain/core dotenv zodInstall TypeScript and the development tools:
npm install -D typescript tsx @types/nodeInitialize TypeScript:
npx tsc --initCreate the following project structure:
langgraph-multi-agent/
├── src/
│ └── index.ts
├── .env
├── package.json
└── tsconfig.jsonAdd your OpenAI API key to the .env file:
OPENAI_API_KEY=your_openai_api_keyReplace the placeholder with your actual API key.
Important: Never expose your API key in frontend code or commit your .env file to Git.
6. Define the Shared State
Let's start by defining the information our graph needs to track.
Open src/index.ts and add the following imports:
import "dotenv/config";
import {
Annotation,
END,
START,
StateGraph,
} from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";Next, create the shared state:
const AgentState = Annotation.Root({
task: Annotation<string>(),
research: Annotation<string>({
reducer: (_, update) => update,
default: () => "",
}),
draft: Annotation<string>({
reducer: (_, update) => update,
default: () => "",
}),
feedback: Annotation<string>({
reducer: (_, update) => update,
default: () => "",
}),
status: Annotation<"research" | "write" | "review" | "revise" | "finish">({
reducer: (_, update) => update,
default: () => "research",
}),
finalAnswer: Annotation<string>({
reducer: (_, update) => update,
default: () => "",
}),
revisionCount: Annotation<number>({
reducer: (_, update) => update,
default: () => 0,
}),
});
type AgentStateType = typeof AgentState.State;Let's understand the fields.
taskstores the user's original request.researchstores the researcher's findings.draftcontains the writer's output.feedbackstores the reviewer's comments.statusdetermines the next workflow step.finalAnswercontains the approved output.revisionCounttracks how many revisions have been requested.
The reducer determines how updates are applied. For most fields, we replace the previous value with the latest update.
The graph's shared state is the communication mechanism between our agents.
7. Create the Language Model
Now initialize the LLM that our agents will use.
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
temperature: 0.2,
});You can change the model according to your requirements and the models available to your account.
A lower temperature is useful when you want relatively consistent outputs, such as structured decisions and content reviews.
The same model instance will be used by all four nodes in this tutorial. Each agent will receive different instructions depending on its role.
8. Build the Researcher Agent
The researcher agent is responsible for preparing useful research notes.
Create the following function:
async function researcherAgent(state: AgentStateType) {
const response = await model.invoke([
{
role: "system",
content: `
You are a research specialist.
Analyze the user's task and produce concise,
well-organized research notes.
Identify the main concepts, important details,
potential limitations, and useful examples.
Do not invent facts, statistics, or sources.
Clearly identify information that requires verification.
`,
},
{
role: "user",
content: state.task,
},
]);
return {
research: String(response.content),
status: "write" as const,
};
}This function receives the current state and sends the user's task to the model.
The model's response is saved in research, and the workflow status changes to write.
The graph can now route execution to the writer.
Notice that the researcher does not need to know how the writer is implemented. Its responsibility is simply to produce useful research notes and update the shared state.
9. Build the Writer Agent
The writer agent takes the research notes and converts them into a structured draft.
async function writerAgent(state: AgentStateType) {
const response = await model.invoke([
{
role: "system",
content: `
You are a professional technical writer.
Create a clear, structured draft based on the
supplied research notes.
Requirements:
- Use descriptive headings.
- Explain technical concepts clearly.
- Include practical examples when appropriate.
- Do not invent facts or unsupported claims.
- Address any review feedback when revising.
`,
},
{
role: "user",
content: `
Task:
${state.task}
Research notes:
${state.research}
Previous review feedback:
${state.feedback || "No previous feedback."}
Create or revise the draft.
`,
},
]);
return {
draft: String(response.content),
status: "review" as const,
revisionCount: state.revisionCount + 1,
};
}The writer uses three pieces of information:
The original task.
The researcher's notes.
Any feedback from a previous review.
This allows the same node to create the initial draft and improve it during later iterations.
The revisionCount field increments each time the writer runs. We'll use it to prevent the system from entering an endless revision loop.
10. Build the Reviewer Agent
The reviewer checks whether the draft satisfies the original task.
We'll use structured output so the model returns a predictable decision rather than an arbitrary text response.
const ReviewSchema = z.object({
approved: z.boolean(),
feedback: z.string(),
});Now implement the reviewer:
async function reviewerAgent(state: AgentStateType) {
const reviewer = model.withStructuredOutput(ReviewSchema);
const result = await reviewer.invoke([
{
role: "system",
content: `
You are a strict content reviewer.
Evaluate the draft against the original task and
the supplied research notes.
Check:
- Accuracy and unsupported claims.
- Completeness.
- Clarity and organization.
- Whether the task has been satisfied.
Approve the draft only if it is sufficiently good.
Otherwise, explain the specific improvements needed.
`,
},
{
role: "user",
content: `
Original task:
${state.task}
Research notes:
${state.research}
Draft:
${state.draft}
`,
},
]);
if (result.approved || state.revisionCount >= 3) {
return {
feedback: result.feedback,
finalAnswer: state.draft,
status: "finish" as const,
};
}
return {
feedback: result.feedback,
status: "revise" as const,
};
}The reviewer has two possible outcomes.
Approved: The draft becomes the final answer.
Needs revision: The reviewer returns feedback and sends the workflow back for another writing attempt.
The revision limit prevents the graph from repeating the writing and review process indefinitely.
In a production application, you may also want to distinguish between an approved draft and a draft finalized because the revision limit was reached. Reaching the limit does not guarantee that the content is correct.
11. Create the Supervisor Agent
The supervisor coordinates the workflow.
Rather than hardcoding every step in the supervisor function, we'll use the current state to decide which stage should run next.
async function supervisorAgent(state: AgentStateType) {
const response = await model.withStructuredOutput(
z.object({
next: z.enum([
"research",
"write",
"review",
"finish",
]),
}),
).invoke([
{
role: "system",
content: `
You are the supervisor of a multi-agent AI system.
Decide which stage should run next.
Rules:
- If research notes are missing, choose research.
- If research exists but no draft exists, choose write.
- If a draft exists but has not been reviewed,
choose review.
- If the reviewer requests revisions, choose write.
- If the review is complete and the draft is finalized,
choose finish.
Return only the structured routing decision.
`,
},
{
role: "user",
content: JSON.stringify({
task: state.task,
hasResearch: Boolean(state.research),
hasDraft: Boolean(state.draft),
feedback: state.feedback,
status: state.status,
revisionCount: state.revisionCount,
hasFinalAnswer: Boolean(state.finalAnswer),
}),
},
]);
// The state is the source of truth for the final decision.
// This prevents the supervisor from accidentally bypassing review.
if (state.status === "finish" && state.finalAnswer) {
return { status: "finish" as const };
}
if (!state.research) {
return { status: "research" as const };
}
if (!state.draft) {
return { status: "write" as const };
}
if (state.status === "revise") {
return { status: "write" as const };
}
if (state.status === "review") {
return { status: "review" as const };
}
if (state.status === "finish") {
return { status: "finish" as const };
}
return {
status: response.next === "finish"
? "review" as const
: response.next,
};
}The supervisor uses the model to evaluate the current workflow context, while deterministic checks ensure that the graph follows the expected sequence.
This combination is important: an LLM can help make decisions, but critical workflow rules should not depend entirely on unconstrained model output.
For a larger system, you could add more specialist agents and more sophisticated routing conditions.
12. Connect the Agents Using LangGraph
Now comes the most important part: building the graph.
Add the following code after the agent functions.
const workflow = new StateGraph(AgentState)
.addNode("supervisor", supervisorAgent)
.addNode("researcher", researcherAgent)
.addNode("writer", writerAgent)
.addNode("reviewer", reviewerAgent)
.addEdge(START, "supervisor")
.addConditionalEdges(
"supervisor",
(state) => state.status,
{
research: "researcher",
write: "writer",
review: "reviewer",
revise: "writer",
finish: END,
},
)
.addEdge("researcher", "supervisor")
.addEdge("writer", "supervisor")
.addEdge("reviewer", "supervisor")
.compile();Let's break down the implementation.
Starting the Graph
.addEdge(START, "supervisor")Every execution begins with the supervisor.
Adding Conditional Edges
.addConditionalEdges(
"supervisor",
(state) => state.status,
{
research: "researcher",
write: "writer",
review: "reviewer",
revise: "writer",
finish: END,
},
)This section determines where the workflow goes after the supervisor executes.
For example:
researchroutes to the researcher.writeroutes to the writer.reviewroutes to the reviewer.reviseroutes back to the writer.finishends the graph.
Returning Control to the Supervisor
.addEdge("researcher", "supervisor")
.addEdge("writer", "supervisor")
.addEdge("reviewer", "supervisor")After a specialist completes its work, control returns to the supervisor.
This is what makes the workflow dynamic rather than a simple sequence of function calls.
Finally, .compile() creates the executable graph.
13. Run the Multi-Agent System
Add the following code to execute the workflow:
async function main() {
const result = await workflow.invoke({
task: `
Explain how vector databases support semantic search.
Include the main concepts, a practical example,
and important limitations.
`,
});
console.log("\n===== FINAL ANSWER =====\n");
console.log(result.finalAnswer);
}
main().catch((error) => {
console.error("Workflow failed:", error);
process.exitCode = 1;
});Run the application:
npx tsx src/index.tsThe system will:
Receive the user's request.
Ask the supervisor to select the next stage.
Generate research notes.
Create a draft.
Review the draft.
Revise the draft if necessary.
Return the finalized output.
The exact result depends on the model's responses and the input task.
Implementation note: The example illustrates the graph architecture and agent responsibilities. Before deploying it, test the code against your installed LangGraph and LangChain package versions, add model-call limits, and validate the supervisor's routing decisions. The reviewer and supervisor use LLMs, so their decisions are not guaranteed to be correct.
14. Visualizing the Workflow
The workflow can be represented as follows:
START
|
v
SUPERVISOR
|
+-------+--------+
| | |
v v v
RESEARCH WRITE REVIEW
| | |
+-------+--------+
|
v
SUPERVISOR
|
+-------+-------+
| |
v v
REVISION FINISH
|
v
WRITERThe important concept is that the supervisor controls the execution path.
Specialist agents do not need to decide which other agents to call. They perform their assigned work and return updates to the shared state.
This separation of responsibilities makes the application easier to understand, test, and extend.
15. How to Improve the System
The basic example demonstrates the architecture, but real-world multi-agent applications often require additional capabilities.
15.1. Add Tools to Specialist Agents
An agent becomes more useful when it can interact with external systems.
For example, the researcher could use:
A web search API.
A document retrieval system.
A vector database.
An internal knowledge base.
A database query tool.
A research agent could retrieve documents from ChromaDB before producing its notes. This would allow it to ground its responses in your own knowledge base rather than relying only on the LLM's existing knowledge.
Tools should have clearly defined permissions, input validation, and error handling.
15.2. Add Human Approval
Some workflows should not execute automatically.
For example, an AI agent that creates marketing content may be allowed to generate a draft but should require approval before publishing it.
LangGraph supports human-in-the-loop workflows through interrupts and checkpointing. This allows execution to pause, preserve state, and resume after a human decision.
For production use, configure a checkpointer and a stable thread identifier so the application can resume the appropriate execution.
15.3. Add Persistent Checkpointing
For a long-running workflow, you may not want to lose all progress when execution stops.
LangGraph supports checkpointing, which can preserve graph state across steps and support recovery, debugging, and resumable execution.
Persistence is especially useful for workflows that involve:
Long-running research.
Human approvals.
Multiple external APIs.
Expensive LLM calls.
Multi-step business processes.
Use a suitable persistent checkpointer in production and configure thread identifiers appropriately.
15.4. Add Retry and Error Handling
LLM calls and external services can fail because of network issues, rate limits, or invalid responses.
A production system should account for:
Temporary API failures.
Rate limiting.
Timeouts.
Invalid structured output.
Missing or incomplete research.
Maximum workflow steps.
Unexpected agent decisions.
Use bounded retries, timeouts, and clear failure states. Avoid retrying indefinitely, as this can increase costs and make the system difficult to debug.
15.5. Monitor Agent Performance
As the number of agents grows, understanding their behavior becomes increasingly important.
You should track:
Model latency.
Token usage.
API costs.
Tool failures.
Agent outputs.
Revision counts.
Final answer quality.
LangSmith can help trace LangChain and LangGraph executions, inspect intermediate steps, and evaluate application performance.
Monitoring makes it easier to identify which agent is causing delays, producing poor results, or consuming unnecessary tokens.
16. Multi-Agent AI Systems vs. Single-Agent Systems
Not every AI application needs multiple agents.
A single-agent system may be sufficient when the task is straightforward and requires only a small number of tool calls.
A multi-agent system becomes more attractive when different tasks benefit from separate instructions, permissions, tools, or evaluation criteria.
Feature | Single-Agent System | Multi-Agent System |
|---|---|---|
Architecture | Usually simpler | More components and routing |
Responsibilities | One main agent handles the task | Responsibilities can be divided |
Complexity | Lower | Higher |
Coordination | Limited | Requires agent coordination |
Debugging | Often easier | Requires tracing multiple steps |
Cost | Often lower | Can be higher due to additional calls |
Best use case | Simple tasks and workflows | Complex tasks with distinct responsibilities |
Multiple agents do not automatically produce better results.
They can introduce additional latency, cost, and failure points. Start with the simplest architecture that meets your requirements, then introduce more agents when the separation provides a measurable benefit.
17. Common Use Cases for LangGraph Multi-Agent Systems
LangGraph can support a wide range of applications.
AI Research Assistants
One agent gathers information, another analyzes it, and a third produces a structured report.
Customer Support Automation
A supervisor routes requests to billing, technical support, or account-management agents.
RAG Applications
Different agents can handle query rewriting, document retrieval, answer generation, and answer evaluation.
Software Development Assistants
Agents can divide work among code analysis, implementation planning, test generation, and code review.
Business Process Automation
Agents can process documents, extract information, validate results, and request human approval when needed.
Content Generation
Research, writing, editing, and SEO analysis can be separated into specialized stages.
The best architecture depends on the task, the tools available, and the level of control required.
18. Best Practices for Production-Ready Multi-Agent Systems
Before deploying a multi-agent application, keep these principles in mind:
Give every agent a clear responsibility. Avoid creating multiple agents that perform the same work without a measurable benefit.
Keep shared state focused. Store only the information that downstream nodes need.
Use structured output for routing decisions. Validate model-generated decisions and enforce important rules in application code.
Limit loops and retries. Set maximum revision counts, execution limits, and timeouts.
Validate agent outputs. Do not assume that a completed LLM call means its output is correct.
Control tool permissions. Give agents only the access they need, especially when tools can modify data or trigger external actions.
Monitor costs and latency. Additional agents may improve quality, but they also introduce extra model calls.
Test individual nodes. Unit-test each agent separately before testing the complete workflow.
Evaluate the complete system. Measure final output quality, not just whether each agent executed successfully.
Use human approval when appropriate. Require explicit review before high-impact or irreversible actions.
These practices help make multi-agent applications more predictable, maintainable, and secure.
Conclusion
Building a multi-agent AI system with LangGraph allows developers to divide complex tasks into specialized operations and coordinate them through a stateful workflow.
In this tutorial, we explored the main components of LangGraph and created a simplified system containing a supervisor, researcher, writer, and reviewer.
The key concepts are:
Nodes perform individual operations.
Edges connect operations.
Shared state passes information between agents.
Conditional routing determines what happens next.
Checkpointing and monitoring help support more reliable applications.
If you're developing AI applications with Node.js, learning LangGraph is a valuable step toward building more advanced agentic workflows.
Start with a small workflow, measure its performance, and add more agents only when they solve a specific problem. With the right architecture, LangGraph can help you build AI systems that are easier to control, evaluate, and extend.
Frequently Asked Questions (FAQs)
1. What is LangGraph used for?
LangGraph is used to build stateful AI workflows and agent applications. It supports graph-based execution, conditional routing, shared state, checkpointing, and human-in-the-loop workflows.
2. Can I use LangGraph with Node.js?
Yes. LangGraph provides a JavaScript/TypeScript package that you can use in Node.js applications. It integrates with the LangChain ecosystem and supported chat models.
3. What is a multi-agent AI system?
A multi-agent AI system contains multiple agents that collaborate on a task. Each agent can have its own instructions, tools, and responsibilities.
4. What is the difference between LangChain and LangGraph?
LangChain provides building blocks for applications powered by language models, including model integrations and tools. LangGraph focuses on orchestrating stateful workflows and agents using graph-based execution.
5. Do multi-agent systems always perform better than single-agent systems?
No. Multi-agent systems can help with complex tasks that benefit from specialized responsibilities, but they may increase latency, cost, and operational complexity. The best choice depends on the use case.
6. Can LangGraph agents use vector databases?
Yes. Agents can interact with vector databases through retrieval tools or application logic. This allows them to retrieve relevant documents and use the results in RAG workflows.
7. Is LangGraph suitable for production applications?
LangGraph can be used in production, but the application still needs appropriate error handling, state persistence, monitoring, security controls, testing, and evaluation.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


