RunnableParallel, then merge their outputs.
Objectives
- Split execution streams to multiple downstream chains concurrently.
- Utilize
RunnableParallelto define dictionary-structured processing branches. - Combine separate analysis branches (such as pros and cons reviews) into a final unified layout.
Parallel Chains Plan
Goal
List the main features of a product, then trigger parallel prompt chains to evaluate the pros and cons of those features separately. Finally, merge both review branches into a unified markdown report.Sample Input
Sample Output
A combined text report containing a “Pros:” evaluation and a “Cons:” evaluation.Plan
- Retrieve features of the product using a primary prompt-model chain.
- Prepare a Pros Analysis chain: takes features as input and outputs pros list.
- Prepare a Cons Analysis chain: takes features as input and outputs cons list.
- Execute both analysis chains concurrently on the retrieved features dictionary using
RunnableParallel. - Pipe the parallel outputs into a merge lambda to combine them into a single report.
Step-by-Step Implementation
Step 1: Base Feature Retrieval
First, we define a prompt template and chain to retrieve the main features of a product.Step 2: Define Branch Chains
Next, we define two downstream helper chains: one to analyze the pros of the features, and one to analyze the cons. We wrap the prompt creation in functions and load them intoRunnableLambda.
Step 3: Run Sub-branches in Parallel
We useRunnableParallel to feed the output of our base features chain into both the pros and cons branches concurrently.
Step 4: Merge Branch Outputs
Finally, we create a function that takes the parallel outputs dictionary and formats them into a final combined report.Complete Combined Code
Below is the complete, consolidated Python script uniting all of the steps above:RunnablePassthrough Example
RunnablePassthrough allows you to pass inputs through unchanged, or combine them with extra values. It is very useful when you want to forward user inputs to multiple downstream steps (like sending a raw question both to a retriever and directly to the final prompt context).
Below is a simple example showing how to pass a single input value through while dynamically injecting extra arguments:
[!NOTE] Implicit Dict Coercion toRunnableParallelYou might notice that in LCEL, we sometimes pipe into a raw Python dictionary containing multiple keys and downstream chains, such as:Under the hood, whenever a dictionary is used within an LCEL pipeline, LangChain implicitly coerces it into aRunnableParallel. During this coercion, any standard Python callables (such as functions or lambdas) are automatically wrapped inside aRunnableLambda.
Practice & Exercises
To reinforce what you’ve learned in this section, practice with the interactive notebook:Practice & Exercises
Practice setting up parallel processing threads, mapping schemas dynamically, and merging concurrent branch results.💻 VS Code | 🚀 Colab | 📥 Download