Runnable Parallel

Open in ColabOpen in GitHub

Overview

This tutorial covers RunnableParallel, a core component of the LangChain Expression Language(LCEL).

RunnableParallel is designed to execute multiple Runnable objects in parallel and return a mapping of their outputs.

This class delivers the same input to each Runnable, making it ideal for running independent tasks concurrently. Moreover, we can instantiate RunnableParallel directly or use a dictionary literal within a sequence.

Table of Contents

References


Environment Setup

Set up the environment. You may refer to Environment Setup for more details.

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

  • You can check out the langchain-opentutorial for more details.

You can alternatively set API keys such as OPENAI_API_KEY in a .env file and load them.

[Note] This is not necessary if you've already set the required API keys in previous steps.

Handling Input and Output

RunnableParallel is useful for manipulating the output of one Runnable within a sequence to match the input format requirements of the next Runnable.

Let's suppose a prompt expects input as a map with keys (context , question).

The user input is simply the question, providing content. Therefore, you'll need to use a retriever to get the context and pass the user input under the question key.

Note that type conversion is handled automatically when configuring RunnableParallel with other Runnables. We don't need to manually wrap the dictionary input provided to the RunnableParallel class.

The following three methods present different initialization approaches that produce the same result:

Using itemgetter as a Shortcut

Python’s itemgetter function offers a shortcut for extracting specific data from a map when it is combined with RunnableParallel .

For example, itemgetter extracts specific keys from a map.

Understanding Parallel Processing Step-by-Step

Using RunnableParallel can easily run multiple Runnables in parallel and return a map of their outputs.

The following example explains how to execute chains that have different input template variables.

Parallel Processing

RunnableParallel is particularly useful for running independent processes in parallel because each Runnable in the map is executed concurrently.

For example, you can see that area_chain, capital_chain, and map_chain take almost the same execution time, even though map_chain runs the other two chains in parallel.

Last updated