liveBook · Manning

RunnablePassthrough

As explained in MongoDB 8.0 in Action, Third Edition

RunnablePassthrough is a LangChain runnable that forwards its input unchanged to a subsequent chain stage.

RunnablePassthrough is a LangChain runnable that forwards its input unchanged to a later chain stage. In retrieval-augmented generation, it commonly preserves the user's question while another parallel branch retrieves relevant context. section 14.5.2 section 14.5.4

A typical retrieval chain uses it to keep inputs available while preparing model context:

  • RunnableParallel prepares separate inputs, such as retrieved context and the original question. section 14.5.2
  • The retriever searches the Atlas Vector Search index for relevant documents. section 14.5.4
  • RunnablePassthrough carries the question forward without transforming it. section 14.5.2
  • ChatPromptTemplate combines the preserved question with retrieved context and metadata before sending the prompt to ChatOpenAI. section 14.5.4
  • StrOutputParser converts the model response into a string for the final chain output. section 14.5.2

Question passthrough in a RAG chain

A chain can retrieve context in one parallel branch and use RunnablePassthrough in another so ChatPromptTemplate receives both values: retrieved documents for context and the user's unchanged question. The resulting prompt can answer a query such as “What indexes does MongoDB support?” using the retrieved documents. section 14.5.4

import os
from langchain_openai import ChatOpenAI
from langchain_community.document_loaders import PyPDFLoader
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import MongoDBAtlasVectorSearch
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables import (
    RunnableLambda,
    RunnableParallel,
    RunnablePassthrough,
)
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pymongo import MongoClient

# Set DB
if os.environ.get("MONGO_URI", None) is None:
    raise Exception("Missing `MONGO_URI` environment variable.")
MONGO_URI = os.environ["MONGO_URI"]

DB_NAME = "langchain"
COLLECTION_NAME = "mongodb"
ATLAS_VECTOR_SEARCH_INDEX_NAME = "default"

client = MongoClient(MONGO_URI)
db = client[DB_NAME]
MONGODB_COLLECTION = db[COLLECTION_NAME]

# Read from MongoDB Atlas Vector Search
vectorstore = MongoDBAtlasVectorSearch.from_connection_string(
    MONGO_URI,
    DB_NAME + "." + COLLECTION_NAME,
    OpenAIEmbeddings(disallowed_special=()),
    index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
)
retriever = vectorstore.as_retriever(search_kwargs={"k": 1})

# RAG prompt
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

# RAG
model = ChatOpenAI()
chain = (
   RunnableParallel({"context": retriever,
➥"question": RunnablePassthrough()})
    | prompt
    | model
    | StrOutputParser()
)


# Add typing for input
class Question(BaseModel):
    __root__: str


chain = chain.with_types(input_type=Question)


def _ingest(url: str) -> dict:
    loader = PyPDFLoader(url)
    data = loader.load()

    # Split docs
    text_splitter = RecursiveCharacterTextSplitter
➥(chunk_size=500, chunk_overlap=0)
    docs = text_splitter.split_documents(data)

    # Insert the documents in MongoDB Atlas Vector Search
    _ = MongoDBAtlasVectorSearch.from_documents(
        documents=docs,
        embedding=OpenAIEmbeddings(disallowed_special=()),
        collection=MONGODB_COLLECTION,
        index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
    )
    return {}

ingest = RunnableLambda(_ingest)

Inspect the complete Python runnable imports and chain configuration, including RunnableParallel, RunnablePassthrough, ChatPromptTemplate, and StrOutputParser. section 14.5.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines the pass-through role and traces its position in retrieval and prompting, but does not detail internal runnable execution.
Examples
Uses a MongoDB Atlas Vector Search chatbot that answers “What indexes does MongoDB support?” from retrieved documents.
What it assumes
Assumes familiarity with LangChain runnables, parallel chains, retrievers, prompts, and model-output parsers.
What you can do after
Configure a LangChain RAG pipeline that preserves questions alongside retrieved context for prompt construction.
How it connects
Connects RunnablePassthrough with RunnableParallel, retrievers, ChatPromptTemplate, ChatOpenAI, and StrOutputParser.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.