Skip to main content

5.3 Sequential Chains

AI-Generated Content

AI-generated content may contain errors. Always verify against official sources.

5.3 Sequential Chains

Key Concepts: Stage 1 output → Stage 2 input · Data transformation between stages

Official Docs: LangChain LCEL — Chaining


What is a Sequential Chain?

A sequential chain passes the output of one step as the input to the next. Each step transforms the data.

Input → Step 1 (Extract) → Step 2 (Summarise) → Step 3 (Translate) → Output

Simple Two-Step Chain

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# Step 1: Summarise
summarise_prompt = ChatPromptTemplate.from_template(
"Summarise the following article in 3 bullet points:\n\n{article}"
)

# Step 2: Translate the summary
translate_prompt = ChatPromptTemplate.from_template(
"Translate the following text to {language}:\n\n{summary}"
)

# Chain them: article → summary → translation
chain = (
{"summary": summarise_prompt | llm | StrOutputParser()}
| translate_prompt
| llm
| StrOutputParser()
)

result = chain.invoke({
"article": "Large language models are neural networks trained to predict the next token...",
"language": "Arabic",
})
print(result)

Passing Multiple Values Between Steps

Use RunnablePassthrough to carry values through a chain without modification:

from langchain_core.runnables import RunnablePassthrough, RunnableLambda
from langchain_core.output_parsers import JsonOutputParser

extract_prompt = ChatPromptTemplate.from_template(
"Extract from this job posting as JSON with keys: title, skills (list), salary:\n\n{posting}"
)

validate_prompt = ChatPromptTemplate.from_template(
"""Given this job data: {job_data}
Assess the role difficulty as: entry / mid / senior.
Respond with JSON: {{\"level\": \"entry|mid|senior\", \"reason\": \"one sentence\"}}"""
)

# Step 1: extract structured data
extract_chain = extract_prompt | llm | JsonOutputParser()

# Step 2: classify from extracted data
classify_chain = (
{"job_data": extract_chain}
| validate_prompt
| llm
| JsonOutputParser()
)

result = classify_chain.invoke({"posting": "Senior ML Engineer at Acme. Python, PyTorch required. $180k/yr."})
print(result) # {"level": "senior", "reason": "..."}

Adding Validation Between Steps

Insert a RunnableLambda for validation:

from langchain_core.runnables import RunnableLambda
from pydantic import BaseModel, ValidationError

class JobData(BaseModel):
title: str
skills: list[str]
salary: str | None

def validate_job(data: dict) -> dict:
try:
return JobData(**data).model_dump()
except ValidationError as e:
raise ValueError(f"Extraction failed schema: {e}")

chain = (
extract_prompt
| llm
| JsonOutputParser()
| RunnableLambda(validate_job) # ← validation gate between steps
| RunnableLambda(lambda x: {"job_data": str(x)})
| validate_prompt
| llm
| JsonOutputParser()
)

Common Mistakes

Common Mistakes
  1. Forgetting to pass all required keys — if Step 2 needs {language} but you only pass {summary}, you get a KeyError. Map all required variables explicitly.
  2. Chaining steps that depend on prior failures — always validate intermediate outputs. A failed extraction silently produces garbage that propagates through all downstream steps.
  3. Over-sequential chains — if steps are independent, run them in parallel (see 5.4) to reduce latency.

Quick Quiz

Test Your Understanding

Q1. What LCEL component lets you pass an upstream value through to a later step without modification?
A1. RunnablePassthrough.

Q2. How do you inject validation logic between two LCEL chain steps?
A2. Wrap a validation function in RunnableLambda and insert it between steps with |.

Q3. What is the main risk of not validating between sequential steps?
A3. A failure in an early step propagates silently, causing all downstream steps to produce incorrect results without any obvious error.


Student Exercise

Exercise 5.3 — News pipeline
Build a 3-step sequential chain: (1) summarise a news article in 3 bullets, (2) extract a list of named entities (people, organisations, locations), (3) classify the article category (politics, sport, technology, finance). Each step should validate its output schema before passing to the next.


Further Reading

Next → 5.4 Parallel & Branching Chains