Chains: The Core Abstraction
You'll learn: How chains connect multiple LangChain components into ordered workflows and how to build your first simple chain.
What is a Chain?
A chain is a sequence of operations that processes data step-by-step. Think of it like a factory assembly line: raw materials (user input) move through different stations (components like prompt templates and LLMs), with each station transforming the data until you get a finished product (final output).
In LangChain, chains link together the components you've already learned—prompt templates, LLMs, and output parsers—into a single, reusable workflow.
Your First Chain: LLMChain
The simplest and most fundamental chain is LLMChain. It combines:
- A prompt template (formats your input)
- An LLM (generates the response)
- Optionally, an output parser (structures the result)
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
# Define your prompt
prompt = PromptTemplate(
input_variables=["product"],
template="Write a catchy slogan for {product}"
)
# Create the chain
llm = OpenAI(temperature=0.7)
chain = LLMChain(llm=llm, prompt=prompt)
# Run it
result = chain.run(product="eco-friendly water bottles")
print(result)
The chain handles the entire flow: it takes your input, applies the prompt template, calls the LLM, and returns the result—all in one .run() call.
Why Use Chains?
Chains make your code cleaner, reusable, and easier to test. Instead of manually passing data between components, you define the workflow once and execute it repeatedly with different inputs.
Key Takeaway: Chains are sequences of operations that connect LangChain components into cohesive workflows, with LLMChain being the foundational pattern combining prompts and LLMs.