Working through this module?0 of 17 done
Module 06 · Page 7 of 20 · 8 sections

Chains in LangChain

What chains are, the chain types, the basic prompt-to-output flow and examples of LLMChain, SequentialChain and RetrievalQA.

6.1

What are Chains?

  • A Chain is a sequence of steps (components) executed in a logical order.
  • It simplifies complex workflows by combining multiple components.
  • Chains can include LLMs, prompts, tools, retrievers, memory, etc.
  • LangChain provides different types of chains for various use cases.
6.2

Why Use Chains?

  • Helps in building multi-step workflows.
  • Easy to combine multiple components.
  • Reduces boilerplate code.
  • Supports input/output parsing.
  • Useful for RAG, agents, document processing, API integrations, etc.
  • Provides a standard interface for complex LLM applications.
6.3

Types of Chains in LangChain

Chain TypeDescription
LLMChainBasic chain with LLM and prompt.
SequentialChainRun multiple chains in sequence.
SimpleSequentialChainSequential chain with simple I/O.
RouterChainRoute input to different chains.
RetrievalQA ChainCombine retriever with LLM for RAG.
ConversationChainMaintain conversation (with memory).
MapReduceChainProcess large documents in parallel.
TransformChainCustom transformation logic.
6.4

Basic Chain Architecture

InputUser query
Prompt TemplateFormat input
LLMOpenAI, Claude, etc.
Output ParserParse response
Final OutputAnswer
6.5

LLMChain

python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)

prompt = PromptTemplate(
    input_variables=["topic"],
    template="Explain {topic} in simple words."
)

chain = LLMChain(llm=llm, prompt=prompt)

response = chain.invoke({"topic": "Microservices"})
print(response["text"])
6.6

SequentialChain

python
from langchain.chains import SequentialChain
from langchain.chains import LLMChain

chain1 = LLMChain(llm=llm, prompt=PromptTemplate(
    input_variables=["topic"],
    template="Give a short summary of {topic}."
))
chain2 = LLMChain(llm=llm, prompt=PromptTemplate(
    input_variables=["summary"],
    template="List key points from this summary: {summary}"
))

sequential_chain = SequentialChain(
    chains=[chain1, chain2],
    input_variables=["topic"],
    output_variables=["summary", "points"]
)

result = sequential_chain.invoke({"topic": "LangChain"})
print(result)
6.7

RetrievalQA Chain (RAG)

python
from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import OpenAIEmbeddings

llm = ChatOpenAI(model="gpt-3.5-turbo")
embedding = OpenAIEmbeddings()
vectorstore = FAISS.load_local("./faiss_index", embedding,
                               allow_dangerous_deserialization=True)
retriever = vectorstore.as_retriever()

chain = RetrievalQA.from_chain_type(llm=llm,
                                    retriever=retriever)

response = chain.invoke({"query": "What is LangChain?"})
print(response["result"])
6.8

Key Takeaways

  • Chains help in creating structured and reusable workflows.
  • Choose the right chain based on your use case.
  • Use the RetrievalQA chain for RAG applications.
  • Sequential chains are useful for multi-step tasks.
  • We can also create custom chains when needed.
  • Chains can be combined with memory, tools and output parsers.