Wednesday, April 1, 2026

RunnableParallel in LangChain With Examples

In the post Chain Using LangChain Expression Language With Examples we saw an example of sequential chain using LCEL. In LangChain there is also a RunnableParallel class which is designed to run multiple components in parallel.

LangChain RunableParallel Class

RunnableParallel is a core component in LangChain Expression Language (LCEL) that allows you to run multiple Runnable objects concurrently on the same input. If you have independent tasks like summarizing a document and creating quiz using the same document then using RunnableParallel you can execute these two workflows simultaneously.

When we say "same input" here, it doesn’t mean prompt has to be exactly same for the parallel tasks. You can pass a single input dictionary where each key corresponds to a different component’s input. Example given later clarifies this point.

RunnableParallel example with Python

Let's say you are given a task to generate content for various social media platforms from a single internal news update. Using RunnableParallel ensures all platform-specific content is generated concurrently.

Task is to generate a press release for LinkedIn where you want to keep the tone professional and for X/Twitter where tone can be a bit casual. You can use parallel chains to generate such tailored content.

Prompts which are used in the example

linkedin_prompt = ChatPromptTemplate.from_messages([
    SystemMessage(content="You are a helpful assistant that generates content for social media platforms."),
    HumanMessagePromptTemplate.from_template("Write a {linkedin_tone} post for {linkedin_platform} about {topic}.")            
])
twitter_prompt = ChatPromptTemplate.from_messages([
    SystemMessage(content="You are a helpful assistant that generates content for social media platforms."),
    HumanMessagePromptTemplate.from_template("Write a {twitter_tone} post for {twitter_platform} about {topic}.")            
])

As you can see, we have the separate place holders {linkedin_tone} and {linkedin_platform} for LinkedIn and {twitter_tone}, {twitter_platform} for Twitter.

In LangChain, RunnableParallel expects a single input dictionary that gets passed to all subchains. Each subchain then decides what to use from that input.

Invoking the chain

So, the chain can be invoked like this-

response = parallel_chain.invoke({
    "topic": topic,
    "linkedin_tone": "professional",
    "linkedin_platform": "LinkedIn",
    "twitter_tone": "casual",
    "twitter_platform": "Twitter"
})

Complete Python program

from langchain.messages import SystemMessage
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_ollama import ChatOllama
from langchain_core.runnables import RunnableParallel
from langchain_core.output_parsers import StrOutputParser
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Define system and human message templates
linkedin_prompt = ChatPromptTemplate.from_messages([
    SystemMessage(content="You are a helpful assistant that generates content for social media platforms."),
    HumanMessagePromptTemplate.from_template("Write a {linkedin_tone} post for {linkedin_platform} about {topic}.")            
])

twitter_prompt = ChatPromptTemplate.from_messages([
    SystemMessage(content="You are a helpful assistant that generates content for social media platforms."),
    HumanMessagePromptTemplate.from_template("Write a {twitter_tone} post for {twitter_platform} about {topic}.")            
])

# Define the output parser
parser = StrOutputParser()

def generate_content(topic: str) -> dict:

    # Initialize the model
    #model = ChatGoogleGenerativeAI(model="gemini-3.1-flash-lite-preview", temperature=0.7)   
    model = ChatOllama(model="llama3.1", temperature=0.7)              

    # Create two chains for LinkedIn and Twitter
    linkedin_chain = linkedin_prompt | model | parser
    twitter_chain = twitter_prompt | model | parser

    # Create a RunnableParallel object to run both chains in parallel
    parallel_chain = RunnableParallel({
        "linkedin": linkedin_chain,
        "twitter": twitter_chain
    })

    # Generate content for both platforms in parallel
    response = parallel_chain.invoke({
        "topic": topic,
        "linkedin_tone": "professional",
        "linkedin_platform": "LinkedIn",
        "twitter_tone": "casual",
        "twitter_platform": "Twitter"
    })

    # Return the generated content as a dictionary
    return response

# Example usage
if __name__ == "__main__":
    topic = "XYZ tech announces new AI product for its gen AI platform"
    generated_content = generate_content(topic)
    print("Generated LinkedIn Post:")
    print(generated_content["linkedin"])
    print("\nGenerated Twitter Post:")
    print(generated_content["twitter"])

Note that, when you construct a RunnableParallel with mapping as given below-

parallel_chain = RunnableParallel({
        "linkedin": linkedin_chain,
        "twitter": twitter_chain
    })

That mapping defines the keys of the output dictionary. Each chain runs in parallel, and the results are collected under those keys. That is why generated content is extracted like this-

generated_content["linkedin"]
generated_content["twitter"]

Output

Copying the content generated for Twitter here as the content generated for LinkedIn is quite long.

Generated Twitter Post:
"BIG NEWS! @XYZTech just dropped a game-changer! Their new AI product is now live on their Gen AI platform, taking AI capabilities to the NEXT LEVEL! What can it do? Stay tuned for the deets! #AI #Tech #Innovation #XYZTech"

That's all for this topic RunnableParallel in LangChain With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. First LangChain Program: Ask Me Anything
  2. LangChain PromptTemplate + Streamlit - Code Generator Example
  3. Messages in LangChain
  4. Java Program to Reverse a Number
  5. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Check if Given String or Number is a Palindrome Java Program
  4. Polymorphism in Java
  5. Difference Between Abstract Class And Interface in Java
  6. Java Automatic Numeric Type Promotion
  7. Java Pass by Value or Pass by Reference
  8. finally Block in Java Exception Handling

No comments:

Post a Comment