LangChain

How to Use Sequential Chains in LangChain?

LangChain is the framework that can be used to build Language Models like chatbots that can be used to ask questions in human languages. After building these models, the user can call them using the queries/prompts in natural language so the model can respond by generating text. The next step after calling the model is to make a sequence or series of calls so the model can use the output of the call and make it the input of other processes.

This guide will illustrate the process of using sequential chains from LangChain.

How to Use Sequential Chains in LangChain?

The LangChain offers multiple sequential methods to use while calling the models like using the SimpleSequentialChain() and SequentialChain() methods.

To learn the process of using the sequential chains in LangChain, simply head inside to the listed steps:

Installing Modules

First, start using the sequential chains by installing the LangChain framework:

pip install langchain

After that, install the OpenAI module that can be used to get its libraries and dependencies to build chains:

pip install openai

Set up the environment for the OpenAI using its API key after signing into the account:

import os
import getpass

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

Method 1: Using SimpleSequentialChain

In this method, import the libraries that can be used to build the LLMChain using the modules installed earlier:

from langchain.chains import LLMChain

#importing different libraries to get prompt templates and LLMs
from langchain.prompts import PromptTemplate

#importing OpenAI libraries to get build LLMs using LangChain

from langchain.llms import OpenAI

Now build the LLM using the OpenAI() method that can be used to write a synopsis using the title of a play:

llm = OpenAI(temperature=.7)
synopsis_template = """you are a writer or reviewer, writing reviews using the names and story of play, you have to write the reviews for the plays

Title: {title}
Playwright: This is a brief survey for the above titles:"""
synopsis_prompt_template = PromptTemplate(input_variables=["title"], template=synopsis_template)
synopsis_chain = LLMChain(llm=llm, prompt=synopsis_prompt_template)

Set up the prompt template for building the LLM using the different titles of the plays and the model will return their reviews:

llm = OpenAI(temperature=.7)
template = """Given the survey of play, You are a reviewer from the playtime, you have to write the reviews for the plays

Play Synopsis:
{synopsis}
Review from a PlayTimes reviewer of the above titles:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template)

Using the SimpleSequentialChain() method using the synopsis and review templates as the parameters:

from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)

Testing Chains

Now, run the chain to get the overall results using the templates for the prompt provided by the user:

review = overall_chain.run("Tragedy at sunset on the beach")

The user can simply run the chain to get a specific outcome from the model like the following code returns the reviews of different plays:

print(review)

Method 2: Using SequentialChain

The next model uses the SequentialChain to build the LLM using the OpenAI() to build a similar model as the previous method does:

llm = OpenAI(temperature=.7)
st = """you are a writer or reviewer, writing reviews using the names and story of play, you have to write the reviews for the plays

Title: {title}

Era:{era}
Playwright: This is a brief survey for the above titles:"""
spt = PromptTemplate(get=["title", "era"], template=st)
synopsis_chain = LLMChain(llm=llm, prompt=spt, output_key="synopsis")

Configure another prompt template by providing the titles for different plays to print their reviews:

llm = OpenAI(temperature=.7)
template = """Given the survey of play, You are a reviewer from the playtime, you have to write the reviews for the plays

Play Synopsis:
{synopsis}
Review from a PlayTimes reviewer of the above titles:"""
pt = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=pt, output_key="review")

Use the SequentialChain library to create a series of chains to get the output (synopsis and reviews) using the input prompt:

from langchain.chains import SequentialChain

#importing SequentialChain library to configure the chain for overall results
overall_chain = SequentialChain(

#configure sequential chain method with multiple arguments like variables
chains=[synopsis_chain, review_chain],
get=["era", "title"],
output_variables=["synopsis", "review"],
verbose=True)

Testing Chains

Simply test the chain to get the synopsis and review of the title provided by the user as the input_variables:

overall_chain({"era": "Victorian England", "title":"Tragedy at sunset on the beach"})

Method 3: Using Memory in Sequential Chains

The last method in this guide is building LLMChain using SequentialChain with the SimpleMemory library. After that build, the model by providing the structure of the prompt and running the chains all in the same code:

from langchain.chains import SequentialChain
from langchain.memory import SimpleMemory

llm = OpenAI(temperature=.7)
template = """Act like a manager for a company running a theater and building posts for publicity,  Use the title of the plays like the era, the date, time and location, the survey of the title, and the review of the play, you have to write the social media post for the plays

Use the context like time and location of the play:
Date and Time: {time}

#setting the template for the prompt using the time and location variables to get the exact information
Location: {location}

Play Synopsis:
{synopsis}
Survey from the PlayTimes reviewer of the above play:
{review}

Social Media Post:
"""
prompt_template = PromptTemplate(input_variables=["synopsis", "review", "time", "location"], template=template)
social_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="social_post_text")
#testing the sequential chain by providing the values for the variables used as the arguments
overall_chain = SequentialChain(
memory=SimpleMemory(memories={"time": "December 25th, 8pm PST", "location": "  London Park"}),

#testing the specific chains by providing the variables used for the arguments and their values
    chains=[synopsis_chain, review_chain, social_chain],
    input_variables=["era", "title"],
    output_variables=["social_post_text"],
    verbose=True)
overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})

Output

The output screenshot displays the chains have been completed successfully using the title of the play:

That is all about the process of using sequential chains in LangChain.

Conclusion

To use the sequential chains in LangChain, simply install the required frameworks to get their dependencies to set up the OpenAI environment. LangChain offers multiple libraries to build and use sequential chains like SimpleSequentialChain, SequentialChain, and SimpleMemory. This guide has explained all the methods of building and then running the chains to build sequences using the LangChain framework.

About the author

Talha Mahmood

As a technical author, I am eager to learn about writing and technology. I have a degree in computer science which gives me a deep understanding of technical concepts and the ability to communicate them to a variety of audiences effectively.