How to Beginner · 3 min read

How to use RunnableLambda in LangChain

Quick answer
Use RunnableLambda in LangChain to wrap any Python function as a runnable component within your chains or pipelines. Instantiate RunnableLambda with a function, then call it with inputs to execute custom logic inline with LangChain workflows.

PREREQUISITES

  • Python 3.8+
  • pip install langchain>=0.2
  • Basic familiarity with LangChain chains and runnables

Setup

Install LangChain if you haven't already and ensure your environment is ready for running Python code with LangChain components.

bash
pip install langchain>=0.2

Step by step

Here is a complete example demonstrating how to create a RunnableLambda that doubles a number and how to run it.

python
from langchain.schema.runnable import RunnableLambda

# Define a simple Python function
def double_number(x: int) -> int:
    return x * 2

# Wrap the function in RunnableLambda
runnable = RunnableLambda(double_number)

# Run the runnable with input
result = runnable.invoke(5)
print(f"Result: {result}")
output
Result: 10

Common variations

You can use RunnableLambda for async functions, integrate it inside LangChain chains, or combine it with other runnables for complex workflows.

python
import asyncio
from langchain.schema.runnable import RunnableLambda

# Async function example
def async_double(x: int) -> int:
    return x * 2

async_runnable = RunnableLambda(async_double)

# Running async runnable
async def main():
    result = await async_runnable.invoke_async(7)
    print(f"Async result: {result}")

asyncio.run(main())
output
Async result: 14

Troubleshooting

If you see errors like TypeError or AttributeError, ensure your function signature matches expected input/output and that you use invoke for sync and invoke_async for async functions.

Key Takeaways

  • Use RunnableLambda to wrap any Python function for seamless integration in LangChain workflows.
  • Invoke synchronous functions with invoke() and asynchronous functions with invoke_async().
  • RunnableLambda enables quick prototyping of custom logic without building full chain classes.
Verified 2026-04
Verify ↗