Subgraphs and Workflow Reuse
🎯 Introduction
As an article workflow grows, review may involve formatting checks, example checks, and report generation. Redefining these nodes in every writing or revision workflow makes reuse difficult. LangGraph subgraphs package a group of tasks into a standalone workflow that other graphs can use. This article covers creating subgraphs and passing state between parent graphs and subgraphs.
🧱 Why Use Subgraphs?
Generating an article and revising an existing article are different operations, but both need review. We can organize review nodes into an independent graph shared by both workflows.
The parent graph decides when to review; the subgraph handles the review steps. The parent does not need to register each internal node. A subgraph can run and be tested independently, or be called as a node in another graph.
🛠 Create a Reusable Review Subgraph
Create review-graph.mjs:
import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';
const ReviewState = new StateSchema({
draft: z.string(),
issue: z.string().default(''),
review: z.string().default(''),
});
function checkExample(state) {
if (!state.draft.includes('For example')) {
return { issue: 'Missing an example' };
}
return { issue: '' };
}
function buildReport(state) {
if (state.issue) {
return { review: state.issue };
}
return { review: 'Review passed' };
}
Add the graph definition:
export const reviewGraph = new StateGraph(ReviewState)
.addNode('check', checkExample)
.addNode('report', buildReport)
.addEdge(START, 'check')
.addEdge('check', 'report')
.addEdge('report', END)
.compile();
This graph can run without a parent graph. Create 06.test-review.mjs:
import { reviewGraph } from './review-graph.mjs';
const result = await reviewGraph.invoke({ draft: 'LangGraph can orchestrate tasks.' });
console.log(result.review);
Run:
node 06.test-review.mjs
Expected output:
Missing an example
Verify the subgraph independently before integrating it into the full workflow to make troubleshooting easier.
🧱 Share State Fields Between Graphs
If the parent and subgraph share the required fields with compatible types and merge semantics, the compiled subgraph can be used directly as a parent node.
Create 06.subgraph.mjs:
import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';
import { reviewGraph } from './review-graph.mjs';
const ArticleState = new StateSchema({
topic: z.string(),
draft: z.string().default(''),
review: z.string().default(''),
});
function writeArticle(state) {
return { draft: `${state.topic} can organize tasks.` };
}
The parent includes topic, the subgraph includes an internal issue field, and both share draft and review. The shared fields have matching meanings and types, so the graphs can connect directly.
Append the following:
const graph = new StateGraph(ArticleState)
.addNode('write', writeArticle)
.addNode('review', reviewGraph)
.addEdge(START, 'write')
.addEdge('write', 'review')
.addEdge('review', END)
.compile();
const result = await graph.invoke({ topic: 'LangGraph' });
console.log(result);
Run:
node 06.subgraph.mjs
Expected output:
{
topic: 'LangGraph',
draft: 'LangGraph can organize tasks.',
review: 'Missing an example'
}
In the parent, reviewGraph executes like any other node. It reads the shared draft and returns the shared review when finished. Its internal issue is not part of the parent state and does not appear in the parent's final result.
🧱 Connect Graphs with Different State Structures
If an existing article system uses article for text and report for review reports, you cannot rely on matching field names to pass state. Add an ordinary parent node to adapt inputs and outputs.
Create 06.adapter.mjs:
import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';
import { reviewGraph } from './review-graph.mjs';
const State = new StateSchema({
article: z.string(),
report: z.string().default(''),
});
async function reviewArticle(state) {
// Map the parent article to the subgraph draft
const result = await reviewGraph.invoke({
draft: state.article,
});
// Map the subgraph result to the parent report
return { report: result.review };
}
Continue with the graph definition:
const graph = new StateGraph(State)
.addNode('review', reviewArticle)
.addEdge(START, 'review')
.addEdge('review', END)
.compile();
const result = await graph.invoke({
article: 'For example: reuse multiple nodes through a subgraph.',
});
console.log(result.report);
Run:
node 06.adapter.mjs
Expected output:
Review passed
The two integration approaches differ as follows:
| Approach | When to use it |
|---|---|
addNode('review', reviewGraph) | Parent and subgraph share compatible state fields |
Call reviewGraph.invoke() inside an ordinary node | Fields differ, or data needs conversion or filtering |
The latter keeps the data structures more independent and makes the review implementation easier to replace. Changes to internal review rules require no parent changes as long as the interface stays the same.
This subgraph has no independent checkpointer, so each invocation starts from fresh input. When the parent uses persistence, the subgraph can inherit checkpointing as needed. Subgraph persistence modes are outside this article's scope.
Reference: Subgraphs.
❓ Questions and Answers
Q1: Should every business function be a subgraph?
No. An ordinary function is enough for a simple calculation. Subgraphs suit reusable workflows with multiple internal steps or branches.
🧪 Exercise
Update checkExample() in review-graph.mjs to first check state.draft.startsWith('# '). If the heading is missing, return { issue: 'Missing a level-one heading' }; otherwise, perform the original example check. Run 06.test-review.mjs and 06.subgraph.mjs and confirm that both return Missing a level-one heading, without changing the parent interface.
🎉 Congratulations! You can now split and reuse workflows with subgraphs.
