Introduction
In the previous articles, we learned how to build workflows using:
RunnableSequenceRunnableParallel- Chat Models
- Prompt Templates
- Output Parsers
For example:
Input
↓
Prompt
↓
Chat Model
↓
Output Parser
↓
Result
These components are powerful, but real applications usually need more than AI models.
Sometimes you need to execute your own JavaScript logic.
For example:
- Transform an input
- Format data
- Calculate a value
- Filter an array
- Call an external API
- Convert an object into a string
- Apply business logic
- Prepare data before sending it to an AI model
This is where RunnableLambda becomes useful.
RunnableLambda allows you to turn a normal JavaScript function into a LangChain Runnable.
In this article, you'll learn:
- What
RunnableLambdais - Why we need it
- How to create one
- Synchronous functions
- Asynchronous functions
- Using
RunnableLambdawithpipe() - Using it with OpenAI
- Using it with Gemini
- Using it with
RunnableSequence - Using it with
RunnableParallel - Real-world examples
- Error handling
- Best practices
- Common mistakes
Let's get started.
What is RunnableLambda?
RunnableLambda is a LangChain Runnable that allows you to execute custom JavaScript or asynchronous JavaScript functions inside a LangChain workflow.
In simple terms:
JavaScript Function
↓
RunnableLambda
↓
LangChain Workflow
For example, you might already have a normal function:
function formatName(name) {
return name.toUpperCase();
}
You can turn it into a Runnable:
const formatNameRunnable =
new RunnableLambda({
func: formatName,
});
Now the function can participate in a LangChain chain.
Why Do We Need RunnableLambda?
Suppose you have this workflow:
User Input
↓
Prompt
↓
AI Model
↓
Parser
What if you need custom logic between the model and parser?
For example:
User Input
↓
Prompt
↓
AI Model
↓
Custom JavaScript Function
↓
Parser
You could manually handle the function.
But that breaks the clean Runnable architecture.
With RunnableLambda, your custom function becomes part of the same workflow.
Runnable
↓
Runnable
↓
RunnableLambda
↓
Runnable
Everything remains composable.
RunnableLambda Architecture
Think of it like this:
Input
↓
RunnableLambda
↓
Custom JavaScript Function
↓
Output
The function receives an input and returns an output.
For example:
const addPrefix = (name) => {
return `Hello ${name}`;
};
The workflow is:
"John"
↓
addPrefix()
↓
"Hello John"
Project Setup
Create a new project:
mkdir runnable-lambda
cd runnable-lambda
npm init -y
Install LangChain:
npm install langchain @langchain/openai @langchain/google-genai dotenv
Project Structure
runnable-lambda/
│
├── index.js
├── .env
└── package.json
Import RunnableLambda
import {
RunnableLambda,
} from "@langchain/core/runnables";
Your First RunnableLambda
Let's start with a simple JavaScript function.
const greet = (name) => {
return `Hello, ${name}!`;
};
Convert it into a Runnable:
const greetRunnable =
new RunnableLambda({
func: greet,
});
Now invoke it:
const result =
await greetRunnable.invoke("John");
console.log(result);
Output:
Hello, John!
That's it.
We've just converted a normal JavaScript function into a LangChain Runnable.
Understanding the Flow
"John"
↓
RunnableLambda
↓
greet()
↓
"Hello, John!"
The important part is that RunnableLambda now behaves like other Runnables.
You can use:
await greetRunnable.invoke("John");
and use it inside larger Runnable workflows.
RunnableLambda with Objects
The input doesn't have to be a string.
It can be an object.
const formatUser = (user) => {
return {
name: user.name.toUpperCase(),
age: user.age,
};
};
Create the Runnable:
const formatUserRunnable =
new RunnableLambda({
func: formatUser,
});
Invoke:
const result =
await formatUserRunnable.invoke({
name: "John",
age: 25,
});
console.log(result);
Output:
{
name: "JOHN",
age: 25
}
RunnableLambda with Arrays
You can also process arrays.
const getNames = (users) => {
return users.map(
(user) => user.name
);
};
Create the Runnable:
const getNamesRunnable =
new RunnableLambda({
func: getNames,
});
Invoke:
const result =
await getNamesRunnable.invoke([
{
name: "John",
age: 25,
},
{
name: "Alice",
age: 28,
},
]);
console.log(result);
Output:
[
"John",
"Alice"
]
Synchronous Functions
A RunnableLambda can wrap a normal synchronous function.
const calculateTotal = (data) => {
return data.price * data.quantity;
};
Create the Runnable:
const totalRunnable =
new RunnableLambda({
func: calculateTotal,
});
Invoke:
const total =
await totalRunnable.invoke({
price: 100,
quantity: 3,
});
console.log(total);
Output:
300
Even though the function itself is synchronous, the Runnable execution uses the standard asynchronous invoke() interface.
Asynchronous Functions
This is where RunnableLambda becomes particularly useful.
Suppose you have an asynchronous function:
const fetchUser = async (id) => {
const response =
await fetch(
`https://api.example.com/users/${id}`
);
return response.json();
};
You can wrap it:
const fetchUserRunnable =
new RunnableLambda({
func: fetchUser,
});
Then:
const user =
await fetchUserRunnable.invoke(101);
console.log(user);
The asynchronous function becomes part of your LangChain workflow.
RunnableLambda with pipe()
This is where things become more interesting.
Suppose we have:
const uppercase =
new RunnableLambda({
func: (text) =>
text.toUpperCase(),
});
Now create another Runnable:
const addPrefix =
new RunnableLambda({
func: (text) =>
`Result: ${text}`,
});
We can compose them:
const chain =
uppercase.pipe(addPrefix);
Invoke:
const result =
await chain.invoke("hello");
Output:
Result: HELLO
The workflow is:
"hello"
↓
uppercase
↓
"HELLO"
↓
addPrefix
↓
"Result: HELLO"
RunnableLambda with OpenAI
Now let's combine custom JavaScript logic with an AI model.
Suppose we want to normalize the user's topic before sending it to OpenAI.
const normalizeTopic =
new RunnableLambda({
func: (topic) =>
topic.trim().toLowerCase(),
});
Create a prompt:
import {
PromptTemplate,
} from "@langchain/core/prompts";
const prompt =
PromptTemplate.fromTemplate(
"Explain {topic} in simple words."
);
Initialize OpenAI:
import { ChatOpenAI } from "@langchain/openai";
const model =
new ChatOpenAI({
model: "gpt-4.1-mini",
});
Now create the chain:
const chain =
normalizeTopic
.pipe((topic) =>
prompt.invoke({ topic })
)
.pipe(model);
Invoke:
const response =
await chain.invoke(
" NODE.JS "
);
console.log(response.content);
The input is normalized before it reaches the model.
A Better Way to Compose the Prompt
Instead of manually calling prompt.invoke(), we can make the transformation return the object expected by the prompt.
const prepareTopic =
new RunnableLambda({
func: (topic) => ({
topic: topic.trim(),
}),
});
Now:
const chain =
prepareTopic
.pipe(prompt)
.pipe(model);
Invoke:
const response =
await chain.invoke(
" Node.js "
);
console.log(response.content);
The workflow becomes:
Raw Input
↓
RunnableLambda
↓
{ topic: "Node.js" }
↓
PromptTemplate
↓
Chat Model
↓
AI Response
This is a much cleaner pattern.
Adding StringOutputParser
If we only want the generated text:
import {
StringOutputParser,
} from "@langchain/core/output_parsers";
const parser =
new StringOutputParser();
Now:
const chain =
prepareTopic
.pipe(prompt)
.pipe(model)
.pipe(parser);
Invoke:
const result =
await chain.invoke(
" Node.js "
);
console.log(result);
The complete pipeline is:
Raw Input
↓
RunnableLambda
↓
Prompt
↓
OpenAI
↓
StringOutputParser
↓
Final String
RunnableLambda with Gemini
The same workflow can use Gemini.
import {
ChatGoogleGenerativeAI,
} from "@langchain/google-genai";
const geminiModel =
new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
});
Create the chain:
const chain =
prepareTopic
.pipe(prompt)
.pipe(geminiModel)
.pipe(parser);
Invoke:
const result =
await chain.invoke(
" React "
);
console.log(result);
Again, only the model changes.
Real-World Example: Data Transformation
Suppose your frontend sends:
{
firstName: "John",
lastName: "Doe",
age: "25"
}
But your AI workflow expects:
{
name: "John Doe",
age: 25
}
Create a transformation:
const transformUser =
new RunnableLambda({
func: (user) => ({
name:
`${user.firstName} ${user.lastName}`,
age: Number(user.age),
}),
});
Now:
const result =
await transformUser.invoke({
firstName: "John",
lastName: "Doe",
age: "25",
});
console.log(result);
Output:
{
name: "John Doe",
age: 25
}
This type of transformation is extremely common in real applications.
Real-World Example: API Integration
Suppose you want to call an external API before sending information to an LLM.
const fetchProduct =
new RunnableLambda({
func: async (productId) => {
const response =
await fetch(
`https://api.example.com/products/${productId}`
);
return response.json();
},
});
Then:
Product ID
↓
RunnableLambda
↓
API
↓
Product Data
↓
Prompt
↓
LLM
This lets you combine your existing backend APIs with LangChain workflows.
Real-World Example: AI Blog Generator
Suppose the user enters:
{
topic: "Node.js Streams",
level: "beginner"
}
First, normalize the input:
const prepareBlogInput =
new RunnableLambda({
func: (data) => ({
topic: data.topic.trim(),
level: data.level.toLowerCase(),
}),
});
Prompt:
const blogPrompt =
PromptTemplate.fromTemplate(`
Write a technical explanation about {topic}
for a {level} developer.
Use simple English and practical examples.
`);
Create the chain:
const blogChain =
prepareBlogInput
.pipe(blogPrompt)
.pipe(openAIModel)
.pipe(parser);
Invoke:
const blog =
await blogChain.invoke({
topic: "Node.js Streams",
level: "Beginner",
});
console.log(blog);
The workflow:
User Input
↓
RunnableLambda
↓
Normalized Data
↓
PromptTemplate
↓
OpenAI
↓
StringOutputParser
↓
Blog Content
RunnableLambda with RunnableParallel
Since RunnableLambda is itself a Runnable, it can also be used with RunnableParallel.
For example:
const uppercase =
new RunnableLambda({
func: (text) =>
text.toUpperCase(),
});
const lowercase =
new RunnableLambda({
func: (text) =>
text.toLowerCase(),
});
Create a parallel workflow:
const parallel =
RunnableParallel.from({
uppercase,
lowercase,
});
Invoke:
const result =
await parallel.invoke(
"Node.js"
);
console.log(result);
Output:
{
uppercase: "NODE.JS",
lowercase: "node.js"
}
RunnableLambda with RunnableSequence
You can also combine it with RunnableSequence.
const sequence =
RunnableSequence.from([
prepareBlogInput,
blogPrompt,
openAIModel,
parser,
]);
Now the entire workflow becomes one Runnable.
const result =
await sequence.invoke({
topic: "Node.js Streams",
level: "beginner",
});
RunnableLambda vs Normal JavaScript Function
You might wonder:
Why not just call a normal function?
For example:
const result =
myFunction(input);
const response =
await model.invoke(result);
You absolutely can.
The advantage of RunnableLambda is composition.
A normal function lives outside the Runnable system.
A RunnableLambda becomes part of it:
Runnable
↓
RunnableLambda
↓
Runnable
↓
Runnable
That means your custom logic can participate in:
pipe()RunnableSequenceRunnableParallelinvoke()batch()- Streaming workflows where applicable
- Other Runnable features
When Should You Use RunnableLambda?
Use RunnableLambda when you need custom application logic inside a LangChain workflow.
Good use cases include:
Data Transformation
API Data
↓
RunnableLambda
↓
Normalized Data
Business Logic
AI Response
↓
RunnableLambda
↓
Validated Business Rule
API Calls
User ID
↓
RunnableLambda
↓
External API
↓
User Data
Formatting
AI Response
↓
RunnableLambda
↓
Formatted Output
Calculations
Input
↓
RunnableLambda
↓
Calculated Value
When Should You NOT Use RunnableLambda?
Don't use RunnableLambda just because you can.
If a simple operation can be handled directly by an existing LangChain component, prefer that component.
For example, don't create unnecessary wrappers around a prompt or model.
Keep the workflow simple.
Error Handling
Because RunnableLambda executes your own code, errors can occur inside the function.
For example:
const divide =
new RunnableLambda({
func: ({ a, b }) => {
if (b === 0) {
throw new Error(
"Cannot divide by zero"
);
}
return a / b;
},
});
Handle errors when invoking the chain:
try {
const result =
await divide.invoke({
a: 10,
b: 0,
});
console.log(result);
} catch (error) {
console.error(
"Workflow failed:",
error.message
);
}
This becomes particularly important when your lambda calls external APIs.
Important: Keep RunnableLambda Small
A common mistake is putting an entire application's business logic inside one lambda.
Avoid:
RunnableLambda
↓
500 lines of code
↓
Everything
Instead, keep it focused:
RunnableLambda
↓
One transformation
For larger logic, move the function into a separate service or utility module and wrap that function with RunnableLambda.
Best Practices
1. Keep functions focused
Each RunnableLambda should ideally perform one clear operation.
2. Handle errors
Custom JavaScript logic can fail just like any other code.
3. Keep external API calls controlled
If your lambda calls an API, consider:
- Timeouts
- Retries
- Rate limits
- Authentication
- Error handling
4. Keep input and output predictable
Document what the lambda expects and what it returns.
For example:
Input:
{
firstName: string,
lastName: string
}
Output:
{
name: string
}
5. Don't overuse RunnableLambda
Use it when custom logic is actually needed.
The goal is a clean workflow, not a workflow filled with unnecessary wrappers.
Common Beginner Mistakes
Mistake 1: Forgetting to return a value
Incorrect:
const processData =
new RunnableLambda({
func: (data) => {
data.name.toUpperCase();
},
});
The function doesn't return anything.
Correct:
const processData =
new RunnableLambda({
func: (data) => {
return data.name.toUpperCase();
},
});
Mistake 2: Returning the wrong data shape
Suppose the next Runnable expects:
{
topic: "Node.js"
}
but your lambda returns:
"Node.js"
The next component may not know how to process it.
Always make sure the output matches the next Runnable's expected input.
Mistake 3: Putting too much logic inside the lambda
Keep lambdas small and focused.
Mistake 4: Forgetting asynchronous behavior
If your function uses fetch() or another asynchronous operation, make the function async.
const fetchData =
new RunnableLambda({
func: async (id) => {
const response =
await fetch(...);
return response.json();
},
});
RunnableLambda in the Runnable Ecosystem
At this point, our Runnable architecture looks like this:
Runnable
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
Prompt Chat Model Parser
│ │ │
└──────────────┼──────────────┘
│
▼
RunnableLambda
And these can be composed using:
pipe()
or:
RunnableSequence
or:
RunnableParallel
This is the real power of the Runnable architecture.
A Complete Example
Let's put everything together.
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
import {
PromptTemplate,
} from "@langchain/core/prompts";
import {
StringOutputParser,
} from "@langchain/core/output_parsers";
import {
RunnableLambda,
RunnableSequence,
} from "@langchain/core/runnables";
const model =
new ChatOpenAI({
model: "gpt-4.1-mini",
});
const prepareInput =
new RunnableLambda({
func: (data) => ({
topic: data.topic.trim(),
level: data.level.toLowerCase(),
}),
});
const prompt =
PromptTemplate.fromTemplate(`
Explain {topic} for a {level} developer.
Use simple English.
Include one practical example.
`);
const parser =
new StringOutputParser();
const chain =
RunnableSequence.from([
prepareInput,
prompt,
model,
parser,
]);
const result =
await chain.invoke({
topic: " Node.js Streams ",
level: "BEGINNER",
});
console.log(result);
The complete execution flow is:
User Input
↓
RunnableLambda
↓
Normalized Input
↓
PromptTemplate
↓
OpenAI
↓
StringOutputParser
↓
Final String
This is a clean, reusable AI workflow.
What's Next?
We've now learned three important Runnable composition patterns:
RunnableSequence
↓
Sequential Workflows
RunnableParallel
↓
Concurrent Workflows
RunnableLambda
↓
Custom JavaScript Logic
But there are situations where you don't want to replace the input.
You want to pass the original input forward while also adding new information.
For example:
Input
↓
┌──────────────→ Original Input
│
└──────────────→ Calculated Value
This is where RunnablePassthrough becomes useful.
In the next article, we'll learn:
Mastering RunnablePassthrough in LangChain.js: Preserve and Pass Data Through AI Workflows
Final Thoughts
RunnableLambda provides a bridge between regular JavaScript code and LangChain's Runnable architecture.
Whenever your AI workflow needs custom logic, you don't have to break out of the LangChain pipeline.
You can simply wrap your function:
const customLogic =
new RunnableLambda({
func: yourFunction,
});
and compose it with everything you've already learned:
Prompt
↓
Model
↓
RunnableLambda
↓
Parser
or:
RunnableLambda
↓
Prompt
↓
Model
or even:
RunnableParallel
├──→ RunnableLambda
├──→ Model
└──→ Another Runnable
The important concept is:
RunnableLambda lets you bring your own JavaScript logic into the LangChain Runnable ecosystem.
Once you understand this, you can build workflows that combine AI capabilities with your application's existing business logic, APIs, utilities, and data-processing functions.
Happy Coding! 🚀