Sequential Chains in LangChain

Last Updated : 1 Sep, 2025

Sequential chains are a type of prompt or model chaining in LangChain which multiple sub-chains (or steps) are linked so that the output from one step becomes the input for the next. This creates a pipeline of processing where a complex task can be decomposed into stages, each handled by a dedicated chain. For example, in a travel itinerary application:

  • One chain could generate activity suggestions based on the input destination.
  • The next chain uses these suggestions to create a detailed daily itinerary.

LangChain supports two main types of sequential chains:

1. Simple Sequential Chain

Simple-Sequential-chain-
Simple Sequential Chain

The simplest form of sequential chains in which each chain in the sequence accepts one input and returns one output. The output of each chain is automatically fed as input to the next chain in the sequence.

  • Use Case: Best suited for straightforward pipelines with linear, single-variable data passing and no complicated branching or multiple inputs/outputs.
  • Example Scenario: You want to generate a summary from an article, then translate that summary into another language.

How it works: We initialize each small task as an individual LLMChain. Then, the SimpleSequentialChain chains these calls automatically:

  • Chain 1: input -> output 1
  • Chain 2: takes output 1 -> output 2 and soon.

They are linear and simple, easy to implement but it is not flexible for advanced workflows.

2. SequentialChain

Sequential-Chain
Sequential Chain

A more flexible variant supporting multiple inputs and outputs for each chain, allowing more complex workflows and interactions.

  • Supports complex workflows where chains might depend on several pieces of information.
  • Can incorporate memory, enabling stateful workflows that maintain context across runs.
  • Suitable for workflows where multiple inputs are combined or outputs split across different keys.
  • Use Case: Suitable when our task requires managing multiple interdependent variables at each stage or incorporating contextual/memory elements.
  • Example Scenario: Generating content, verifying it for policy compliance, enriching it with metadata and then packaging everything together.

Use of Sequential Chains

  • Modularity: Break complex tasks into smaller logical building blocks.
  • Clear Input/Output Flow: Each chain has well-defined inputs and outputs.
  • Reusability: Individual chains easily reused/composed into different workflows.
  • Error Handling: Intermediate results methodically verifiable.
  • Context Management: Memory integration (in SequentialChain) enables context/state persistence across chains.
  • Scalability: Helps scale up from simple single-step LLM calls to complex multi-step applications.

Step-by-Step Building Sequential Chains

1. Simple Sequential Chain implementation in LangChain

Step 1: Import Libraries: We will import the necessary libraries for our model, such as PromptTemplate, ChatOpenAI, RunnableSequence, os.

Python
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableSequence
import os

Step 2: Set API Key

  • Stores our OpenAI API key as an environment variable.(We can also use Gemini API Key.)
  • Needed for authentication with OpenAI’s models.
Python
os.environ["OPENAI_API_KEY"] = "your_api_key_here"

Step 3: Create LLM Instance: We will create a LLM example,

  • Creates a chat model object.
  • This model will process prompts.
Python
llm = ChatOpenAI(model="gpt-3.5-turbo")

Step 4: Define Prompt Templates: We will define the templates,

  • company_prompt: expects product and will ask the model for a company name.
  • slogan_prompt: expects company_name and will ask the model for a slogan.
Python
company_prompt = PromptTemplate(
    input_variables=["product"],
    template="Generate a creative company name for a product that is {product}."
)

slogan_prompt = PromptTemplate(
    input_variables=["company_name"],
    template="Write a catchy slogan for the company named {company_name}."
)

Step 5: Create Runnable Chains and Build Sequential Chain: We will create runnable chains along with building sequential chains,

  • | (pipe operator) connects a prompt to the LLM.
  • We combine both chains into pipeline.
Python
company_chain = company_prompt | llm
slogan_chain = slogan_prompt | llm

book_summary_chain = RunnableSequence(company_chain, slogan_chain)

Step 6: Invoke Chain: We will run the chain,

Python
result = book_summary_chain.invoke({"product": "eco-friendly water bottles"})
print("Generated slogan:\n", result.content)

Output:

simplesequentialchain
Simple Sequential Chain

2. Sequential Chain implementation in LangChain

Step 1: Import Libraries: We will import the necessary libraries for our model, such as PromptTemplate, ChatOpenAI, RunnableSequence, os.

Python
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableSequence
import os

Step 2: Set API Key

  • Stores our OpenAI API key as an environment variable.(We can also use Gemini API Key.)
  • Needed for authentication with OpenAI’s models.
Python
os.environ["OPENAI_API_KEY"] = "your_api_key_here"

Step 3: Create LLM Example: We will create a LLM instance,

  • Creates a chat model object.
  • This model will process prompts.
Python
llm = OpenAI(model="gpt-3.5-turbo-instruct")

Step 4: First Chain: Company Name, We will define the first chain,

  • PromptTemplate takes the variable {product}.
  • LLMChain runs the prompt through llm and saves the result under "company_name".
Python
company_prompt = PromptTemplate(
    input_variables=["product"],
    template="Generate a creative company name for a product that is {product}."
)
company_chain = LLMChain(llm=llm, prompt=company_prompt,
                         output_key="company_name")

Step 5: Second Chain: Slogan, We will,

  • Uses output of first chain (company_name) as input.
  • Produces the final slogan string under "slogan".
Python
slogan_prompt = PromptTemplate(
    input_variables=["company_name"],
    template="Write a catchy slogan for the company named {company_name}."
)
slogan_chain = LLMChain(llm=llm, prompt=slogan_prompt, output_key="slogan")

Step 6: Sequential Chain

  • Runs company_chain first, then feeds its output into slogan_chain.
  • Declares inputs (product) and outputs (company_name, slogan).
  • verbose=True → logs each step.
Python
sequential_chain = SequentialChain(
    chains=[company_chain, slogan_chain],
    input_variables=["product"],
    output_variables=["company_name", "slogan"],
    verbose=True
)

Step 7: Run Pipeline: We will run the chain and it will give,

  • A generated company name.
  • A matching slogan.
Python
result = sequential_chain.invoke({"product": "eco-friendly water bottles"})
print("Company name:", result["company_name"])
print("Slogan:", result["slogan"])

Output:

Sequentialchain
Sequential Chains

Simple Sequential Chain vs. Sequential Chain

Let's see the differences between the two types of sequential chains,

Features

SimpleSequentialChain

Sequential Chain

Description

Simplest form of chaining multiple steps linearly.

More advanced chain supporting multiple inputs/outputs.

Input/Output Handling

Single input and single output per step, passed linearly.

Supports named multiple inputs and outputs for each chain step.

Flexibility

Less flexible, good for straightforward pipelines.

Highly flexible, supports complex workflows and branching.

Chaining Style

Implicit chaining via positional output-input flow.

Explicit chaining via named variable mapping

Use Cases

Simple linear tasks like prompt → response → reformulation.

Complex workflows needing multiple variables, conditional logic or context tracking.

Advantages

  • Modular workflow: breaks complex tasks into smaller, reusable steps.
  • Automatic flow: passes outputs of one chain as inputs to the next.
  • Clarity: makes pipelines easy to understand, debug and maintain.
  • Scalability: supports adding more steps without changing structure.
  • Transparency: step-by-step results can be logged and tracked.

Limitations

  • Error propagation: one wrong output can ruin all following steps.
  • Performance: slower since each step requires a separate LLM call.
  • Cost: multiple steps = more tokens and API charges.
  • Rigid structure: only supports linear (one-after-another) flow, no branching.
Comment

Explore