AI Hints
Home›LangChain Tutorial›Passthrough, Routing, Fallbacks
LangChain · Lesson 22 of 120

RunnablePassthrough

Carrying data along.

⏱ 2 min read▶ Video at 22:55🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

In a chain, each step only sees the output of the step before it. But sometimes a later step needs the original input too. Runnable passthrough carries data along, unchanged.

RunnablePassthrough
From the video: RunnablePassthrough
  • Each step sees the last output
  • Later steps need the input
  • Pass it through

Keeping the input

Here, a runnable parallel runs two branches. Question uses runnable passthrough, so it's just the original input. Length is a small function that counts its words. Run it. The output keeps the original question, next to the new value. This is exactly how retrieval chains keep the user's question, while adding documents beside it.

passthrough.pypython
from langchain_core.runnables import RunnableParallel, RunnablePassthrough

step = RunnableParallel(
    question=RunnablePassthrough(),
    length=lambda q: len(q.split()),
)
print(step.invoke("Do you have any books about the sea?"))
Output
{'question': 'Do you have any books about the sea?', 'length': 8}

Adding fields with assign

Assign is a related trick. It keeps every key of a dictionary input, and adds new ones, computed from it. Run it. The title is still there, and a new key, title length, has been added. Later steps can use both.

assign.pypython
from langchain_core.runnables import RunnablePassthrough

add_length = RunnablePassthrough.assign(title_length=lambda d: len(d["title"]))
print(add_length.invoke({"title": "Pride and Prejudice"}))
Output
{'title': 'Pride and Prejudice', 'title_length': 19}

Summary

Runnable passthrough passes the input through unchanged, and assign adds new keys while keeping the old ones. Next, choosing different paths for different inputs.

Key takeaways
  • RunnablePassthrough()
  • Keep the original input
  • .assign(new=fn)
Next up: Routing — choosing a path