RunnablePassthrough from langchain_core.runnables to:
- Act as a no-op placeholder in a chain.
- Inject or override keys in the input dictionary at runtime with
assign.
1. Basic Prompt → LLM → Parser Chain
Start by creating a minimal chain that sends a prompt to an LLM and parses the raw string output:This chain uses
ChatPromptTemplate to format inputs, ChatOpenAI to call OpenAI’s chat API, and StrOutputParser to convert the model’s response to a plain string.2. Adding a No-Op with RunnablePassthrough
You can insertRunnablePassthrough anywhere to forward data unchanged. It’s useful as a placeholder for future logic or debugging:
Use passthrough steps to reserve spots in your pipeline for metrics, logging, or future transformations.
3. Verifying the Output
Even with a passthrough at the tail, the result remains identical:4. Injecting or Overriding Inputs with assign
The true power of RunnablePassthrough lies in its assign method, which lets you inject or override dictionary keys before they reach downstream components. For instance, you can fix the topic to "movies", so callers only need to supply question:
- The first passthrough forwards
{"question": ...}. assign(topic=lambda _: "movies")adds"topic": "movies".- The prompt, LLM, and parser receive both keys.
assign by itself:
Ensure that your assignment functions return serializable values. Non-serializable objects may break downstream components or logging.
Common assign Patterns
| Method | Purpose | Example | |
|---|---|---|---|
assign(key=value) | Static value injection | assign(topic=lambda _: "news") | |
assign(key=function) | Dynamic or computed value injection | assign(timestamp=lambda _: datetime.utcnow().isoformat()) | |
| Multiple assignments chained | Inject several keys at once | `assign(a=lambda _:1) | RunnablePassthrough.assign(b=lambda _:2)` |
5. Summary
You’ve learned how to:- Use
RunnablePassthroughas a no-op placeholder for debugging or future pipeline steps. - Employ
assignto inject or override keys in your chain inputs. - Maintain a clean and testable pipeline structure with minimal boilerplate.
RunnableLambda for custom transformations.