---
title: Chains in LangChain
description: "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…"
url: "https://csestudy247.com/docs/chains-in-langchain/"
updated: "2026-08-15"
category: LangChain
---

# Chains in LangChain

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:

1. Design a prompt.
2. Send it to the LLM.
3. Parse the output.
4. (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.

```python

                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.

```python

                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.

    RunnableBranch - E-commerce Support     RunnableBranch — E-commerce Customer Support    Customer Question  ↓   RunnableBranch  ↓      Order?    Order Chain      Return?    Return Chain      Payment?    Payment Chain       ↓    Appropriate Answer

```python

                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.

    Think about the default format of a response from ChatGPT.    [Discuss it](#)

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.

    Consider how an LLM would talk to a database or a web service.    [Discuss it](#)

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.

    Think about the input requirements of a standard software function or library.    [Discuss it](#)

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()

    The name of this function describes the goal of providing the model with a specific output shape.    [Discuss it](#)

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.

    Recall if the code crashed when a string was assigned to an integer field in the video demo.    [Discuss it](#)

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

    This class serves as the 'base' for all Pydantic-based data structures.    [Discuss it](#)

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.

    Think about Pydantic's type coercion capabilities.    [Discuss it](#)

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.

    Think about 'universal' data formats versus language-specific libraries.    [Discuss it](#)

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.

    This function is used to provide extra context or constraints about a specific field.    [Discuss it](#)

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.

    This concept is covered when working with models lacking native structured output support.    [Discuss it](#)

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.

    This method is closely related to how LLMs interact with external tools and functions.    [Discuss it](#)

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.

    This involves using a utility from Python's typing module along with a default value.    [Discuss it](#)

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."]

[Chains in LangChain | Generative AI using LangChain | Video 7 | CampusX](https://www.youtube.com/embed/5hjrPILA3-8?list=PLKnIA16_RmvaTbihpo4MtzVm4XOQa0ER0)
