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)
Sometimes you want to execute multiple tasks at the same time using the same input. For example, generating “Notes” and a “Quiz” from the same document simultaneously.
from langchain_core.runnables import RunnableParallel
# Define two separate chains
notes_chain = prompt_notes | model | parser
quiz_chain = prompt_quiz | model | parser
# Combine them into a parallel chain
parallel_chain = RunnableParallel({
"notes": notes_chain,
"quiz": quiz_chain
})
# The final chain can then merge these results into a third prompt
final_chain = parallel_chain | prompt_merge | model | parser
C. Conditional Chains (RunnableBranch)
Conditional chains allow your application to take different paths based on the LLM’s output. A classic example is Sentiment Analysis: if a review is positive, send a “Thank You”; if negative, send an “Apology”.
from langchain_core.runnables import RunnableBranch
# Define a branch logic
branch_chain = RunnableBranch(
(lambda x: x["sentiment"] == "positive", positive_response_chain),
(lambda x: x["sentiment"] == "negative", negative_response_chain),
default_chain # Executed if no conditions are met
)
# Combine classification with branching
full_chain = classification_chain | branch_chain
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.”]