Conditional Branches and Loops
🎯 Introduction
When a review finds issues, the article needs revision and another review. An article that already passes should not consume more model calls. Ordinary edges have fixed destinations and cannot choose the next node based on review results. This article covers conditional edges, loops, and Command, including state-based routing, loop limits, and transient node failures.
🧱 Route Based on Review Results
Previously, the workflow ended after review regardless of the outcome. Now, articles that fail should be revised and reviewed again, while articles that pass should finish immediately.
passed = true
passed = false
revise
Allow at most two revisions to prevent an endless loop. If the article still fails at that limit, end the workflow with its failed status intact for the application to handle.
Create 04.routing.mjs and define the workflow state:
import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';
const ArticleState = new StateSchema({
draft: z.string(),
passed: z.boolean().default(false),
feedback: z.string().default(''),
revisions: z.number().default(0),
});
Add the review and revision nodes:
function reviewArticle(state) {
// Simulate a review rule: the article must contain an example
if (state.draft.includes('For example')) {
return { passed: true, feedback: 'Review passed' };
}
return { passed: false, feedback: 'Missing an example' };
}
function reviseArticle(state) {
return {
draft: `${state.draft}\nFor example: split generation and review into two nodes.`,
revisions: state.revisions + 1,
};
}
The review node provides a conclusion, and the revision node edits the article. Define routing separately to decide what happens after review:
function routeAfterReview(state) {
// Review passed, or the revision limit has been reached
if (state.passed || state.revisions >= 2) {
return END;
}
return 'revise';
}
The routing function runs after the review node. It receives the state with the review updates already merged and returns the next node's name or END. The program applies business rules directly, without asking a model to choose a path.
🛠 Create Conditional Edges and Loops
Continue appending to the file:
const graph = new StateGraph(ArticleState)
.addNode('review', reviewArticle)
.addNode('revise', reviseArticle)
.addEdge(START, 'review')
.addConditionalEdges('review', routeAfterReview, ['revise', END])
.addEdge('revise', 'review')
.compile();
The three arguments to addConditionalEdges() are the source node, routing function, and possible destinations. An ordinary edge has a fixed destination; a conditional edge chooses its destination at runtime.
You do not need to write a while loop. Connecting revise back to review allows the graph to run the review node again.
Add the execution code:
const stream = await graph.stream({
draft: 'LangGraph can orchestrate tasks.',
}, {
streamMode: 'updates',
recursionLimit: 20,
});
for await (const update of stream) {
console.log(update);
}
Run:
node 04.routing.mjs
Expected output:
{ review: { passed: false, feedback: 'Missing an example' } }
{ revise: { draft: 'LangGraph can orchestrate tasks.\nFor example: split generation and review into two nodes.', revisions: 1 } }
{ review: { passed: true, feedback: 'Review passed' } }
The first review fails and triggers revision. The second passes, so routing returns END.
Change the input to draft: 'For example: use nodes to execute tasks.' and run it again. Expect just one review update:
{ review: { passed: true, feedback: 'Review passed' } }
recursionLimit caps underlying execution steps. It is not the number of allowed article revisions. Use a state field such as revisions to enforce business limits.🧱 Update State and Route with Command
Sometimes a node can determine the next step as soon as it produces a result. Return a Command to combine state updates and routing in one return value.
Add Command to the LangGraph import in 04.routing.mjs. Replace reviewArticle() with:
function reviewArticle(state) {
if (state.draft.includes('For example')) {
return new Command({
update: { passed: true, feedback: 'Review passed' },
goto: END,
});
}
let next = 'revise';
if (state.revisions >= 2) {
next = END;
}
return new Command({
update: { passed: false, feedback: 'Missing an example' },
goto: next,
});
}
updatespecifies the state updates from this node.gotospecifies the next node to execute.
Remove the unused routeAfterReview() function and replace the graph definition with:
const graph = new StateGraph(ArticleState)
.addNode('review', reviewArticle, { ends: ['revise', END] })
.addNode('revise', reviseArticle)
.addEdge(START, 'review')
.addEdge('revise', 'review')
.compile();
ends declares the destinations this node can reach through Command. Do not add conditional edges for review here, or fixed outgoing edges alongside the command: those additional paths may also execute.
Restore the original input without an example and run it again:
node 04.routing.mjs
Expect the same output as in the conditional-edge example:
{ review: { passed: false, feedback: 'Missing an example' } }
{ revise: { draft: 'LangGraph can orchestrate tasks.\nFor example: split generation and review into two nodes.', revisions: 1 } }
{ review: { passed: true, feedback: 'Review passed' } }
Prefer conditional edges for routing based only on state, so workflow rules remain easy to inspect together. Use Command when a node needs to update state and choose a path at the same time.
🧱 Handle Transient Node Failures
A failed article review is a normal business outcome, not a program exception. A temporary network error while calling a review service, however, can be handled by retrying the node instead of generating the whole article again.
Create 04.retry.mjs:
import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';
const State = new StateSchema({
review: z.string().default(''),
});
let attempts = 0;
function reviewArticle() {
attempts++;
console.log('Review service calls:', attempts);
// Simulate a transient failure on the first call
if (attempts === 1) {
throw new Error('Simulated network failure');
}
return { review: 'Review passed' };
}
Continue with:
const graph = new StateGraph(State)
.addNode('review', reviewArticle, {
retryPolicy: {
maxAttempts: 2,
},
})
.addEdge(START, 'review')
.addEdge('review', END)
.compile();
const result = await graph.invoke({});
console.log(result.review);
Run:
node 04.retry.mjs
Expected application logs (the framework may also log retry messages):
Review service calls: 1
Review service calls: 2
Review passed
maxAttempts: 2 includes the initial attempt, allowing at most one retry. If the second attempt fails, the task ends with an exception. Real applications can use retryOn to select retryable errors. A retry restarts the node function, rather than just the failed line. Do not blindly retry operations with side effects, such as publishing an article twice.
References: Graph API, Fault tolerance.
❓ Questions and Answers
Q1: Is retrying a node the same as revising an article after a failed review?
No. A retry happens when a node throws an exception and the framework runs it again according to its retry policy. A revision loop is a normal business branch after the node successfully returns a review result.
🧪 Exercise
In 04.routing.mjs, change reviseArticle() to return only { revisions: state.revisions + 1 }, leaving the text unchanged. Run it and observe that review keeps failing, but revision runs at most twice and the workflow ends after the third review. The final passed value is still false; workflow completion does not mean the article passed.
🎉 Congratulations! You can now control workflow paths based on business outcomes.
