In LangChain, a Chain is a way to connect multiple individual components into a single pipeline. Instead of manually handling the output of a prompt, sending it to a model, and then parsing the result, a Chain automates this flow so that the output of one step becomes the input for the next.
1. Why Use Chains? #
When building LLM applications, you rarely have just one step. Usually, you need to:
- Design a prompt.
- Send it to the LLM.
- Parse the output.
- (Optionally) Use that output to trigger another LLM call.
Doing this manually is tedious and error-prone. Chains allow you to create a declarative pipeline where you only need to provide the initial input, and the entire sequence executes automatically.
2. LangChain Expression Language (LCEL) #
LangChain uses a specific syntax to build chains called LCEL. It uses the pipe operator (|) to join components.
Basic Syntax:
chain = prompt | model | parser
In this example, the prompt output is piped into the model, and the model’s output is piped into the parser.
3. Types of Chains with Code Examples #
A. Simple Sequential Chain
This is a linear chain where steps happen one after another.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 1. Setup Components
prompt = PromptTemplate.from_template("Generate 5 facts about {topic}")
model = ChatOpenAI()
parser = StrOutputParser()
# 2. Create the Chain
chain = prompt | model | parser
# 3. Invoke the Chain
result = chain.invoke({"topic": "cricket"})
print(result)
B. Parallel Chains (RunnableParallel)
In LangChain, RunnableParallel is used when you want to run multiple chains/tasks at the same time and collect all their outputs into a single dictionary.
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o-mini")
summary_prompt = ChatPromptTemplate.from_template(
"Give a short explanation of {topic}"
)
question_prompt = ChatPromptTemplate.from_template(
"Create 3 interview questions about {topic}"
)
summary_chain = summary_prompt | model
question_chain = question_prompt | model
parallel_chain = RunnableParallel(
summary=summary_chain,
questions=question_chain
)
result = parallel_chain.invoke({
"topic": "LangChain"
})
print(result)
C. Conditional Chains (RunnableBranch)
RunnableBranch is a LangChain component that selects and executes one chain based on a condition. It works like if-elif-else logic, routing the input to the appropriate chain.
Real-World Example: E-commerce Customer Support #
Imagine an online shopping website.
A customer can ask:
"Where is my order?"→ Order Tracking"I want to return my shoes"→ Returns"I received a damaged product"→ Complaint"What payment methods do you accept?"→ Payment- Anything else → General Support
Instead of sending every question to the same prompt, RunnableBranch routes the question to the appropriate chain.
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableBranch
# -----------------------------
# Model
# -----------------------------
model = ChatOllama(
model="gemma3:1b"
)
# -----------------------------
# Prompts
# -----------------------------
order_prompt = ChatPromptTemplate.from_template(
"""
You are an order tracking support agent.
Help the customer with their order-related question.
Customer question:
{question}
"""
)
return_prompt = ChatPromptTemplate.from_template(
"""
You are a product return support agent.
Help the customer understand the return or refund process.
Customer question:
{question}
"""
)
payment_prompt = ChatPromptTemplate.from_template(
"""
You are a payment support agent.
Help the customer with their payment-related question.
Customer question:
{question}
"""
)
general_prompt = ChatPromptTemplate.from_template(
"""
You are a general customer support agent.
Answer the customer's question clearly and politely.
Customer question:
{question}
"""
)
# -----------------------------
# Chains
# -----------------------------
order_chain = order_prompt | model
return_chain = return_prompt | model
payment_chain = payment_prompt | model
general_chain = general_prompt | model
# -----------------------------
# Conditional Routing
# -----------------------------
branch_chain = RunnableBranch(
(
lambda x: any(
word in x["question"].lower()
for word in ["order", "delivery", "track", "shipment"]
),
order_chain
),
(
lambda x: any(
word in x["question"].lower()
for word in ["return", "refund", "replace"]
),
return_chain
),
(
lambda x: any(
word in x["question"].lower()
for word in ["payment", "card", "upi", "transaction"]
),
payment_chain
),
general_chain
)
# -----------------------------
# Test
# -----------------------------
questions = [
"Where is my order?",
"I want to return my shoes",
"Can I pay using UPI?",
"Do you have a store in Delhi?"
]
for question in questions:
print("\nUSER:", question)
result = branch_chain.invoke({
"question": question
})
print("AI:", result.content)
4. Visualizing Your Chain
A powerful feature in LangChain is the ability to visualize the structure of the pipeline you have built. You can use the get_graph().print_ascii() method to see the flow of data.
# Print the visual graph of the chain
print(chain.get_graph().print_ascii())
5. Summary of Key Components #
| Component | Purpose |
|---|---|
| invoke() | The method used to trigger the start of a chain. |
| RunnableParallel | Used to run multiple chains in parallel using the same input. |
| RunnableBranch | Used to implement “If-Else” logic within a chain. |
| RunnableLambda | Used to convert a standard Python function into a component that can be used in a chain. |
Conclusion
Chains are the “DNA” of LangChain. They transform isolated components into automated, complex workflows. By mastering Sequential, Parallel, and Conditional chains, you can build sophisticated AI agents that handle diverse tasks with minimal manual intervention.
Chains Quiz #
Q.1 In the context of Large Language Models (LLMs), what is primarily considered an 'unstructured' output?
A JSON object with key-value pairs.
A natural language text response.
A CSV file containing tabular data.
A SQL query generated for a database.
Explanation
By default, LLMs generate natural language text, which is considered unstructured because it does not follow a predefined machine-readable format like JSON.
Q.2 What is the most significant advantage of generating structured output from an LLM?
It reduces the token usage and cost of the model.
It allows the LLM to integrate easily with other machines and systems.
It prevents the model from hallucinating facts.
It makes the LLM response more human-readable.
Explanation
Structured output enables seamless integration with APIs, databases, applications, and other software systems because the output follows a predictable format.
Q.3 When building an AI Agent that uses a calculator tool, why is structured output necessary?
Structured output increases the mathematical accuracy of the LLM.
Agents are only allowed to communicate via JSON schemas.
Calculators cannot interpret natural language instructions directly.
Tools are designed to verify the sentiment of the user prompt.
Explanation
Calculator tools expect structured inputs such as numbers and parameters. They cannot reliably understand free-form natural language responses from an LLM.
Q.4 Which LangChain function is used to simplify the process of obtaining structured data from models that natively support it?
format_as_pydantic()
invoke_as_json()
parse_output_structure()
with_structured_output()
Explanation
LangChain’s with_structured_output() method automatically configures supported models to return data matching a schema such as Pydantic, TypedDict, or JSON Schema.
Q.5 What is a major limitation of using Python's 'TypedDict' for defining output schemas in LangChain?
It requires a separate license for commercial use.
It cannot be converted into a JSON format.
It does not support string-based keys.
It does not perform runtime data validation.
Explanation
TypedDict provides static type hints for developers but performs no runtime validation, so invalid data types may pass through unnoticed.
Q.6 In Pydantic, which class must your schema inherit from to define a structured data model?
SchemaObject
BaseModel
DataClass
StructuredDict
Explanation
Every Pydantic schema inherits from BaseModel, which provides validation, parsing, serialization, and other useful features.
Q.7 What happens in Pydantic if you pass the string '25' to a field defined as an integer?
The model ignores the input and sets the value to 'None'.
Pydantic throws an Immediate ValidationError.
Pydantic automatically converts (coerces) the string to the integer 25.
The value is stored as a string regardless of the definition.
Explanation
Pydantic performs type coercion whenever possible. Since ’25’ is a valid numeric string, it is automatically converted into the integer 25.
Q.8 Which scenario would most benefit from using 'JSON Schema' over 'Pydantic' for defining structured output?
When running models that do not support JSON mode.
A project built entirely in Python.
A project where the schema needs to be shared between Python and JavaScript systems.
When the developer wants the simplest possible syntax.
Explanation
JSON Schema is language-independent, making it ideal for projects where multiple programming languages need to use the same schema definition.
Q.9 What is the purpose of the 'Field' function in Pydantic schemas?
To increase the speed of the LLM's response generation.
To define metadata like descriptions and constraints for specific attributes.
To encrypt the data before sending it to the LLM.
To tell the LLM which database table to use.
Explanation
Field() allows developers to add descriptions, validation rules, default values, and constraints that help both Pydantic and the LLM understand the expected data.
Q.10 If you are using an open-source model like 'TinyLlama' that does not natively support structured output, what is the recommended approach in LangChain?
Use Pydantic with the 'with_structured_output' function.
Convert the TinyLlama model into a GPT-4 model.
Use Output Parsers to process the raw text output.
Force the model to use 'function_calling' mode.
Explanation
For models without native structured output support, LangChain recommends using Output Parsers to transform raw text responses into structured data.
Q.11 In the 'with_structured_output' function, when should you typically set the 'method' parameter to 'function_calling'?
When you want the output in a raw string format.
When you are using a model that only supports JSON mode.
When the model needs to call a human for help.
When using OpenAI models that support specialized API calls for tools.
Explanation
The function_calling method leverages OpenAI’s tool-calling capability to produce reliable structured outputs and is the recommended approach for supported models.
Q.12 How can you make a field optional in a Pydantic model so that it doesn't cause an error if the LLM fails to provide it?
Set the type to 'NoneType'.
Wrap the type in 'Optional' and provide a default value of 'None'.
Delete the field from the class definition.
Use the 'skip_validation' decorator.
Explanation
(or type | None in newer Python versions) with a default value of None, allowing the field to be omitted without raising a validation error.”]