How to use RunnablePassthrough in LangChain
Quick answer
Use
RunnablePassthrough in LangChain to create a chain component that returns its input unchanged, useful for debugging or chaining without transformation. Instantiate it and call invoke or use it in a RunnableSequence to pass data through unchanged.PREREQUISITES
Python 3.8+pip install langchain>=0.2Basic knowledge of LangChain runnables
Setup
Install LangChain if you haven't already and import RunnablePassthrough from langchain.schema.runnable. Ensure your environment uses Python 3.8 or higher.
pip install langchain>=0.2 Step by step
This example shows how to instantiate RunnablePassthrough and use it to pass input through unchanged. It also demonstrates chaining it with another runnable.
from langchain.schema.runnable import RunnablePassthrough
# Create a passthrough runnable
passthrough = RunnablePassthrough()
# Input data
input_data = "Hello, LangChain!"
# Invoke passthrough to get the same input back
output = passthrough.invoke(input_data)
print("Output:", output)
# Example chaining with RunnableSequence
from langchain.schema.runnable import RunnableSequence
# Define a simple runnable that uppercases text
class RunnableUppercase(RunnablePassthrough):
def invoke(self, input):
return input.upper()
uppercase = RunnableUppercase()
# Chain passthrough and uppercase
chain = RunnableSequence([passthrough, uppercase])
result = chain.invoke("chain me")
print("Chained output:", result) output
Output: Hello, LangChain! Chained output: CHAIN ME
Common variations
- Use
RunnablePassthroughin async contexts withainvoke. - Combine with other runnables like
RunnableMaporRunnableSequencefor complex pipelines. - Use with LangChain's
Runnableinterface to integrate with LLMs or other tools.
import asyncio
async def async_example():
passthrough = RunnablePassthrough()
result = await passthrough.ainvoke("async input")
print("Async output:", result)
asyncio.run(async_example()) output
Async output: async input
Troubleshooting
- If
RunnablePassthroughdoes not return input, verify you are callinginvokeorainvokecorrectly. - Ensure LangChain version is 0.2 or higher to have
RunnablePassthrough. - Check that input types are compatible;
RunnablePassthroughreturns exactly what it receives.
Key Takeaways
- Use
RunnablePassthroughto pass inputs unchanged in LangChain pipelines. - Combine
RunnablePassthroughwith other runnables for flexible chaining. - Invoke
invokeorainvokemethods to run the passthrough synchronously or asynchronously.