Introduction
In the previous articles, we learned about several important Runnable components:
-
RunnableSequence -
RunnableParallel -
RunnableLambda -
RunnablePassthrough -
RunnableAssign
Each one solves a different problem.
But there is one important capability we haven't covered yet:
Conditional execution.
In a real application, we don't always want every input to follow the same workflow.
For example, imagine a customer support chatbot.
A user might ask:
"How do I reset my password?"
That should go to an account support workflow.
Another user might ask:
"Where is my order?"
That should go to an order support workflow.
And someone else might ask:
"Can I get a refund?"
That should go to a refund workflow.
The workflow becomes:
┌──→ Account Chain
│
User Input ─────────┼──→ Order Chain
│
└──→ Refund Chain
We need some logic to decide which chain should execute.
This is where RunnableBranch becomes useful.
In this article, we'll learn:
-
What
RunnableBranchis -
Why conditional workflows are useful
-
How
RunnableBranchworks -
How to create conditions
-
How to create branches
-
Default branches
-
Using
RunnableBranchwithRunnableLambda -
Using it with OpenAI
-
Using it with Gemini
-
Combining multiple conditions
-
Combining
RunnableBranchwithRunnableSequence -
Combining
RunnableBranchwithRunnableParallel -
Real-world examples
-
Error handling
-
Best practices
-
Common mistakes
Let's get started.
What is RunnableBranch?
RunnableBranch allows you to choose which Runnable should execute based on a condition.
In simple terms:
Input
↓
Check Condition
↓
┌───────────────┐
│ Which branch? │
└───────────────┘
↓
Selected Runnable
↓
Output
For example:
Input
↓
Is age >= 18?
│
├── Yes → Adult Workflow
│
└── No → Minor Workflow
The important point is:
Only the selected branch is executed.
This is different from RunnableParallel, where multiple branches can execute concurrently.
Why Do We Need RunnableBranch?
Without conditional routing, we might write:
if (condition) {
await chainA.invoke(input);
} else {
await chainB.invoke(input);
}
That's perfectly valid JavaScript.
But LangChain provides RunnableBranch so that the conditional logic itself becomes part of the Runnable architecture.
Instead of:
JavaScript Logic
↓
LangChain
↓
More JavaScript Logic
we can build:
Runnable
↓
RunnableBranch
↓
Selected Runnable
This keeps the workflow composable.
RunnableBranch Architecture
A simple branch looks like:
┌──→ Chain A
│
Input ──→ Condition
│
└──→ Chain B
For multiple conditions:
┌──→ Chain A
│
Input → Condition 1 ─────┤
│
├──→ Condition 2
│ │
│ ├──→ Chain B
│ │
│ └──→ Default
You can think of it as an AI workflow equivalent of:
if / else if / else
Project Setup
Let's create a new project.
mkdir runnable-branch
cd runnable-branch
npm init -y
Install the required packages:
npm install @langchain/core @langchain/openai @langchain/google-genai dotenv
Project Structure
runnable-branch/
│
├── index.js
├── .env
└── package.json
Configure API Keys
Create .env:
OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key
And add:
node_modules/
.env
to .gitignore.
Import RunnableBranch
import {
RunnableBranch,
RunnableLambda,
} from "@langchain/core/runnables";
Your First RunnableBranch
Let's start without an AI model.
Suppose we want to determine whether a number is positive or negative.
Create two Runnables:
const positive =
RunnableLambda.from(
() => "The number is positive."
);
const negative =
RunnableLambda.from(
() => "The number is negative."
);
Now create the branch:
const branch =
new RunnableBranch({
branches: [
[
(input) => input >= 0,
positive,
],
],
default: negative,
});
Invoke it:
const result =
await branch.invoke(10);
console.log(result);
Output:
The number is positive.
Try:
const result =
await branch.invoke(-5);
console.log(result);
Output:
The number is negative.
Understanding the Code
This condition:
(input) => input >= 0
checks the input.
If it returns:
true
the positive Runnable executes.
Otherwise, the default Runnable executes.
The workflow is:
Input: 10
↓
10 >= 0 ?
↓
true
↓
Positive Runnable
For -5:
Input: -5
↓
-5 >= 0 ?
↓
false
↓
Default Runnable
RunnableBranch as if/else
The previous example is equivalent to:
if (input >= 0) {
return "The number is positive.";
}
return "The number is negative.";
So a simple mental model is:
RunnableBranch is conditional routing inside the Runnable architecture.
Multiple Conditions
Now let's create three branches:
Age
↓
Age < 13
↓
Child
Age >= 13 && age < 18
↓
Teenager
Age >= 18
↓
Adult
Create the Runnables:
const child =
RunnableLambda.from(
() => "Child"
);
const teenager =
RunnableLambda.from(
() => "Teenager"
);
const adult =
RunnableLambda.from(
() => "Adult"
);
Create the branch:
const ageBranch =
new RunnableBranch({
branches: [
[
(age) => age < 13,
child,
],
[
(age) =>
age >= 13 && age < 18,
teenager,
],
],
default: adult,
});
Invoke:
console.log(
await ageBranch.invoke(10)
);
console.log(
await ageBranch.invoke(16)
);
console.log(
await ageBranch.invoke(25)
);
Output:
Child
Teenager
Adult
How Multiple Branches Work
RunnableBranch evaluates the conditions in order.
Conceptually:
Condition 1
↓
true? ── Yes → Branch 1
No
↓
Condition 2
↓
true? ── Yes → Branch 2
No
↓
Default Branch
This means branch order matters.
We'll discuss this more in the common mistakes section.
Default Branch
The default branch is used when none of the conditions match.
For example:
const branch =
new RunnableBranch({
branches: [
[
(input) => input === "openai",
openAIChain,
],
[
(input) => input === "gemini",
geminiChain,
],
],
default: fallbackChain,
});
If the input is:
openai
OpenAI is selected.
If the input is:
gemini
Gemini is selected.
If the input is:
something-else
the fallback chain is selected.
Conditions Can Be Functions
The condition is generally a function that receives the input.
For example:
(input) => input.type === "technical"
or:
(input) => input.score >= 80
or:
(input) =>
input.language === "javascript"
This gives you a lot of flexibility.
Async Conditions
Conditions can also be asynchronous when the routing decision requires an async operation.
For example:
const checkUser =
async (userId) => {
const response =
await fetch(
`https://api.example.com/users/${userId}`
);
const user =
await response.json();
return user.isPremium;
};
The condition can then perform an asynchronous check before selecting a branch.
However, for simple conditions, keep them synchronous. Don't introduce asynchronous operations unless they are actually necessary.
RunnableBranch with OpenAI
Now let's build a practical AI example.
Suppose we have two types of questions:
Technical Question
General Question
We want technical questions to go through a technical prompt and general questions to go through a general prompt.
Initialize OpenAI
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
const model =
new ChatOpenAI({
model: "gpt-4.1-mini",
});
Import PromptTemplate
import {
PromptTemplate,
} from "@langchain/core/prompts";
Create two prompts:
const technicalPrompt =
PromptTemplate.fromTemplate(`
You are a technical assistant.
Answer the following technical
question with a practical example:
{question}
`);
const generalPrompt =
PromptTemplate.fromTemplate(`
You are a helpful assistant.
Answer the following question
in simple and friendly language:
{question}
`);
Add Output Parser
import {
StringOutputParser,
} from "@langchain/core/output_parsers";
const parser =
new StringOutputParser();
Create the chains:
const technicalChain =
technicalPrompt
.pipe(model)
.pipe(parser);
const generalChain =
generalPrompt
.pipe(model)
.pipe(parser);
Create the Branch
We can determine whether the question is technical using a simple property:
const branch =
new RunnableBranch({
branches: [
[
(input) =>
input.type === "technical",
technicalChain,
],
],
default: generalChain,
});
Invoke:
const result =
await branch.invoke({
type: "technical",
question:
"What is the Node.js event loop?",
});
console.log(result);
The technical chain will be selected.
General Question
Now:
const result =
await branch.invoke({
type: "general",
question:
"What is your favorite programming language?",
});
console.log(result);
Since:
input.type === "technical"
is false, the default branch executes.
The workflow becomes:
Question
↓
type === technical?
│
├── Yes → Technical Prompt → OpenAI
│
└── No → General Prompt → OpenAI
RunnableBranch with Gemini
We can also create a Gemini branch.
Initialize Gemini:
import {
ChatGoogleGenerativeAI,
} from "@langchain/google-genai";
const geminiModel =
new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
});
Create a Gemini chain:
const geminiChain =
technicalPrompt
.pipe(geminiModel)
.pipe(parser);
Now we can route based on a model preference:
const branch =
new RunnableBranch({
branches: [
[
(input) =>
input.provider === "openai",
technicalChain,
],
[
(input) =>
input.provider === "gemini",
geminiChain,
],
],
default: technicalChain,
});
Invoke with OpenAI:
const result =
await branch.invoke({
provider: "openai",
type: "technical",
question:
"Explain Node.js streams.",
});
Invoke with Gemini:
const result =
await branch.invoke({
provider: "gemini",
type: "technical",
question:
"Explain Node.js streams.",
});
The same RunnableBranch can route the request to different providers.
Building a Customer Support Router
Let's build a more realistic example.
Suppose we have three categories:
Account
Order
Refund
Input:
{
category: "order",
question: "Where is my order?"
}
Create prompts:
const accountPrompt =
PromptTemplate.fromTemplate(`
You are an account support assistant.
Help the user with:
{question}
`);
const orderPrompt =
PromptTemplate.fromTemplate(`
You are an order support assistant.
Help the user with:
{question}
`);
const refundPrompt =
PromptTemplate.fromTemplate(`
You are a refund support assistant.
Help the user with:
{question}
`);
Create chains:
const accountChain =
accountPrompt
.pipe(model)
.pipe(parser);
const orderChain =
orderPrompt
.pipe(model)
.pipe(parser);
const refundChain =
refundPrompt
.pipe(model)
.pipe(parser);
Create the branch:
const supportRouter =
new RunnableBranch({
branches: [
[
(input) =>
input.category === "account",
accountChain,
],
[
(input) =>
input.category === "order",
orderChain,
],
[
(input) =>
input.category === "refund",
refundChain,
],
],
default:
new RunnableLambda(
() =>
"Sorry, I couldn't identify your request."
),
});
Now:
const result =
await supportRouter.invoke({
category: "order",
question:
"Where is my order?",
});
console.log(result);
The order support chain is selected.
Building a Language Router
Another common use case is routing based on programming language.
Suppose your application receives:
{
language: "javascript",
question: "How does async/await work?"
}
You can route to different specialized chains:
┌──→ JavaScript Chain
│
Question ───────────┼──→ Python Chain
│
└──→ Java Chain
Example:
const router =
new RunnableBranch({
branches: [
[
(input) =>
input.language === "javascript",
javascriptChain,
],
[
(input) =>
input.language === "python",
pythonChain,
],
],
default: generalProgrammingChain,
});
This is useful when different programming languages require different system instructions or specialized behavior.
AI-Based Routing
So far, we've used a property such as:
input.category
But what if the user doesn't provide a category?
For example:
"How can I change my password?"
We need to determine:
Account?
Order?
Refund?
We can use an LLM as a classifier.
The workflow becomes:
User Question
↓
Classifier
↓
Category
↓
RunnableBranch
↓
Selected Chain
For example:
"Where is my order?"
↓
Classifier
↓
"order"
↓
Order Chain
This is a very common architecture for AI applications.
LLM Router Example
Create a classification prompt:
const classifierPrompt =
PromptTemplate.fromTemplate(`
Classify the following customer
question into exactly one category:
account
order
refund
Question:
{question}
Return only the category.
`);
Create a classifier chain:
const classifier =
classifierPrompt
.pipe(model)
.pipe(parser);
Now the classifier can produce:
order
or:
account
or:
refund
We can then use that classification to route the request.
This is a powerful pattern, but there is an important consideration:
The classifier output must be predictable.
Using structured output or a schema is often safer than relying on unrestricted text. We'll explore more robust routing patterns later in the series.
RunnableBranch + RunnableLambda
Because conditions and branches can work with other Runnables, we can combine RunnableBranch with RunnableLambda.
For example:
const normalize =
RunnableLambda.from(
(input) => ({
...input,
category:
input.category.toLowerCase(),
})
);
Then:
Input
↓
Normalize
↓
RunnableBranch
↓
Selected Chain
Create the workflow:
const workflow =
normalize.pipe(
supportRouter
);
Invoke:
const result =
await workflow.invoke({
category: "ORDER",
question:
"Where is my order?",
});
The category is normalized before routing.
RunnableBranch + RunnableSequence
RunnableBranch can also be one step inside a larger sequence.
For example:
Input
↓
Prepare Data
↓
RunnableBranch
↓
Selected AI Chain
↓
Parser
↓
Final Output
Conceptually:
const workflow =
RunnableSequence.from([
prepareInput,
router,
]);
This works because both components implement the Runnable interface.
RunnableBranch + RunnableParallel
You can also place parallel workflows inside branches.
For example:
┌──→ Summary
│
Technical Input ────┤
└──→ Code Explanation
while:
General Input
↓
General Chain
The workflow becomes:
Input
↓
Branch
│
├── Technical
│ ↓
│ Parallel
│ ├──→ Summary
│ └──→ Explanation
│
└── General
↓
General Chain
This shows how Runnable components can be nested.
RunnableBranch + RunnableAssign
We can also route an object and then enrich it.
For example:
Input
↓
RunnableBranch
↓
Selected Chain
↓
RunnableAssign
↓
Enriched Result
This can be useful in applications where different branches produce specialized information that needs to be added to the original request.
Real-World Example: AI Interview Assistant
Imagine an interview assistant.
The user selects:
{
role: "frontend",
question:
"What is React reconciliation?"
}
We can route:
Role
│
├── Frontend → React/Frontend Chain
│
├── Backend → Node.js Chain
│
└── Database → SQL Chain
Each branch can use different prompts and even different models.
For example:
const interviewRouter =
new RunnableBranch({
branches: [
[
(input) =>
input.role === "frontend",
frontendChain,
],
[
(input) =>
input.role === "backend",
backendChain,
],
[
(input) =>
input.role === "database",
databaseChain,
],
],
default: generalInterviewChain,
});
This is a clean way to build specialized AI assistants.
Real-World Example: Blog Generator
Suppose your blogging application supports:
-
Beginner articles
-
Intermediate articles
-
Advanced articles
Input:
{
topic: "Node.js Streams",
level: "advanced"
}
Route it:
Level
│
├── Beginner → Beginner Prompt
│
├── Intermediate → Intermediate Prompt
│
└── Advanced → Advanced Prompt
Each branch can have different instructions.
For example, the advanced branch might require:
-
Internal implementation details
-
Performance considerations
-
Production patterns
-
Error handling
-
Advanced examples
While the beginner branch might focus on simple explanations.
Real-World Example: Multi-Model Routing
Suppose your application supports:
OpenAI
Gemini
The frontend sends:
{
provider: "gemini",
question: "Explain closures."
}
The router selects Gemini.
const modelRouter =
new RunnableBranch({
branches: [
[
(input) =>
input.provider === "openai",
openAIChain,
],
[
(input) =>
input.provider === "gemini",
geminiChain,
],
],
default: openAIChain,
});
This makes model selection part of the workflow.
Real-World Example: Difficulty-Based Responses
Suppose an education application stores a student's level:
{
level: "beginner",
question: "What is a closure?"
}
Route based on the level:
Beginner
↓
Simple Explanation
Intermediate
↓
Detailed Explanation
Advanced
↓
Deep Technical Explanation
This can make an AI application much more personalized.
Conditions Should Be Simple
A good condition is easy to understand:
(input) =>
input.category === "order"
or:
(input) =>
input.level === "advanced"
Avoid putting large amounts of business logic directly into the condition.
Instead, use a separate function:
const isAdvanced =
(input) =>
input.level === "advanced";
Then:
[
isAdvanced,
advancedChain,
]
This makes the workflow easier to read and test.
Branch Order Matters
Consider:
const branch =
new RunnableBranch({
branches: [
[
(input) => input.age >= 18,
adultChain,
],
[
(input) => input.age >= 21,
specialAdultChain,
],
],
default: childChain,
});
For:
age = 25
the first condition is already true:
input.age >= 18
So the second branch will never be reached.
The correct order depends on your business rules.
If you want the more specific condition first:
const branch =
new RunnableBranch({
branches: [
[
(input) => input.age >= 21,
specialAdultChain,
],
[
(input) => input.age >= 18,
adultChain,
],
],
default: childChain,
});
Now 25 reaches specialAdultChain.
Default Branch Is Important
Always think about what happens when no condition matches.
For example:
Known Category
↓
Specific Chain
Unknown Category
↓
Fallback Chain
A good fallback prevents your workflow from behaving unexpectedly.
For example:
const fallback =
RunnableLambda.from(
() =>
"I couldn't determine the request type."
);
Then:
default: fallback
Error Handling
Runnable branches can contain AI models, APIs, and custom code.
So normal error handling is still important.
try {
const result =
await router.invoke(input);
console.log(result);
} catch (error) {
console.error(
"Routing failed:",
error
);
}
You should also consider what happens when:
-
The classifier fails.
-
A model is unavailable.
-
A condition throws an error.
-
A branch API call fails.
-
The input has an unexpected shape.
Common Beginner Mistakes
Mistake 1: Forgetting the default branch
If no condition matches, you need a sensible fallback.
For example:
default: fallbackChain
Mistake 2: Putting broad conditions first
Remember that branches are evaluated in order.
A broad condition can prevent later, more specific conditions from ever being reached.
Mistake 3: Mutating the input inside conditions
Avoid doing this:
(input) => {
input.category =
input.category.toLowerCase();
return true;
}
A condition should ideally just determine whether a branch should execute.
Do transformations separately using RunnableLambda.
Mistake 4: Using RunnableBranch when all branches should execute
If every branch needs to run, use:
RunnableParallel
not:
RunnableBranch
Remember:
RunnableBranch
↓
Choose one
while:
RunnableParallel
↓
Run multiple
Mistake 5: Putting too much logic inside conditions
Avoid:
(input) => {
// 50 lines of business logic
// API calls
// transformations
// validation
// calculations
return true;
}
Keep conditions focused.
RunnableBranch vs RunnableParallel
This is one of the most important comparisons.
RunnableParallel
Runs multiple independent branches:
┌──→ A
│
Input ────────┼──→ B
│
└──→ C
Use it when you need multiple results.
RunnableBranch
Chooses one branch:
┌──→ A
│
Input → Check ┼──→ B
│
└──→ C
Use it when only one workflow should execute.
RunnableBranch vs RunnableLambda
RunnableLambda
Executes custom JavaScript:
Input
↓
Function
↓
Output
RunnableBranch
Uses conditions to select a workflow:
Input
↓
Condition
↓
Selected Runnable
They can work together.
For example:
Input
↓
RunnableLambda
↓
Normalize
↓
RunnableBranch
↓
Selected Chain
RunnableBranch vs Normal if/else
Normal JavaScript:
if (input.type === "technical") {
return technicalChain.invoke(input);
}
return generalChain.invoke(input);
RunnableBranch:
const router =
new RunnableBranch({
branches: [
[
(input) =>
input.type === "technical",
technicalChain,
],
],
default: generalChain,
});
The second approach keeps the routing logic inside the Runnable workflow.
This becomes more valuable as your workflow grows.
Complete OpenAI Example
Let's build a complete example.
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
import {
PromptTemplate,
} from "@langchain/core/prompts";
import {
StringOutputParser,
} from "@langchain/core/output_parsers";
import {
RunnableBranch,
RunnableLambda,
} from "@langchain/core/runnables";
const model =
new ChatOpenAI({
model: "gpt-4.1-mini",
});
const parser =
new StringOutputParser();
const technicalPrompt =
PromptTemplate.fromTemplate(`
You are a technical interviewer.
Answer this question with:
1. Definition
2. Practical explanation
3. Example
Question:
{question}
`);
const generalPrompt =
PromptTemplate.fromTemplate(`
Answer the following question
in simple English.
Question:
{question}
`);
const technicalChain =
technicalPrompt
.pipe(model)
.pipe(parser);
const generalChain =
generalPrompt
.pipe(model)
.pipe(parser);
const fallback =
RunnableLambda.from(
() =>
"Please provide a valid question type."
);
const router =
new RunnableBranch({
branches: [
[
(input) =>
input.type === "technical",
technicalChain,
],
],
default: generalChain,
});
const result =
await router.invoke({
type: "technical",
question:
"What is the Node.js event loop?",
});
console.log(result);
The workflow:
┌──→ Technical Chain
│
Input → Type Check ──┤
│
└──→ General Chain
Complete Gemini Example
The same architecture can use Gemini.
import {
ChatGoogleGenerativeAI,
} from "@langchain/google-genai";
const geminiModel =
new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
});
const geminiTechnicalChain =
technicalPrompt
.pipe(geminiModel)
.pipe(parser);
Now route to Gemini:
const router =
new RunnableBranch({
branches: [
[
(input) =>
input.provider === "gemini",
geminiTechnicalChain,
],
[
(input) =>
input.provider === "openai",
technicalChain,
],
],
default: generalChain,
});
Invoke:
const result =
await router.invoke({
provider: "gemini",
type: "technical",
question:
"Explain Node.js streams.",
});
console.log(result);
A More Advanced Workflow
Let's combine several Runnable concepts.
We can build:
User Input
↓
RunnableLambda
↓
Normalize Input
↓
RunnableBranch
│
├── Technical
│ ↓
│ RunnableParallel
│ ├── Summary
│ └── Example
│
└── General
↓
General Chain
This demonstrates something important about LangChain:
Runnable components are composable.
You don't have to choose only one abstraction.
You can combine:
-
Sequence
-
Parallel
-
Lambda
-
Passthrough
-
Assign
-
Branch
to build larger workflows.
Best Practices
1. Keep conditions simple
Good:
(input) =>
input.category === "technical"
Avoid putting entire workflows inside conditions.
2. Order conditions carefully
More specific conditions should generally appear before broader conditions.
3. Always think about the fallback
Ask:
What happens if none of my conditions match?
4. Validate input before routing
If your workflow expects:
{
type: "technical",
question: "..."
}
make sure those fields exist before the branch runs.
5. Keep branches focused
Each branch should represent a clear workflow.
For example:
Technical → Technical Assistant
Order → Order Assistant
Refund → Refund Assistant
6. Use structured classification when using an LLM router
If an LLM determines the route, don't rely blindly on arbitrary text.
Prefer predictable outputs such as:
technical
general
or structured output such as:
{
category: "technical"
}
This makes routing more reliable.
When Should You Use RunnableBranch?
Use RunnableBranch when your application needs to choose between different workflows.
Good examples include:
-
Customer support routing
-
Programming language routing
-
AI model selection
-
User-level personalization
-
Difficulty-based education
-
Content classification
-
Intent classification
-
RAG routing
-
Tool selection
-
Multi-agent routing
When Should You Not Use RunnableBranch?
Don't use it when all workflows need to execute.
Use RunnableParallel instead.
Don't use it just to perform data transformation.
Use RunnableLambda.
Don't use it when steps simply depend on each other.
Use RunnableSequence.
The decision becomes:
Need sequential execution?
↓
RunnableSequence
Need multiple results?
↓
RunnableParallel
Need custom JavaScript?
↓
RunnableLambda
Need to preserve input?
↓
RunnablePassthrough
Need to enrich an object?
↓
RunnableAssign
Need conditional routing?
↓
RunnableBranch
What's Next?
We've now covered the core Runnable building blocks:
RunnableSequence
RunnableParallel
RunnableLambda
RunnablePassthrough
RunnableAssign
RunnableBranch
These components allow us to create sophisticated workflows.
But there is another important concept in LangChain:
How do we execute the same workflow for multiple inputs efficiently?
For example:
[
"What is React?",
"What is Node.js?",
"What is Next.js?"
]
Instead of calling:
await chain.invoke(input1);
await chain.invoke(input2);
await chain.invoke(input3);
LangChain provides:
chain.batch(...)
This allows us to process multiple inputs through the same Runnable workflow.
In the next article, we'll learn:
Mastering batch() in LangChain.js: Process Multiple Inputs Efficiently (OpenAI + Gemini)
Final Thoughts
RunnableBranch is one of the most useful components when building real-world AI workflows.
The core idea is simple:
Evaluate conditions and route the input to the appropriate Runnable.
Instead of:
Every Input
↓
Same Workflow
we can build:
┌──→ Workflow A
│
Input → Condition
│
├──→ Workflow B
│
└──→ Default Workflow
This makes AI applications much more flexible.
For example, a customer support application can route:
Account Question
↓
Account Chain
Order Question
↓
Order Chain
Refund Question
↓
Refund Chain
An education application can route:
Beginner
↓
Simple Explanation
Intermediate
↓
Detailed Explanation
Advanced
↓
Deep Technical Explanation
And an AI application can even route between providers:
┌──→ OpenAI
│
Request → Router
│
└──→ Gemini
The key difference to remember is:
RunnableBranch chooses one workflow, while RunnableParallel executes multiple workflows.
Once you combine RunnableBranch with RunnableSequence, RunnableParallel, RunnableLambda, and RunnableAssign, you can build highly flexible AI workflows while keeping your code modular and composable.
Happy Coding! 🚀